15-03-2017 - Bram Smulders
Bram Smulders
bramsmulders.com
@bramsmulders
bramsmulders.github.io/slides
if ('serviceWorker' in navigator) {
window.addEventListener('load', function() {
navigator.serviceWorker.register('/sw.js').then(function(registration) {
// Registration was successful
console.log('ServiceWorker registration successful with scope: ', registration.scope);
}).catch(function(err) {
// registration failed :(
console.log('ServiceWorker registration failed: ', err);
});
});
}
const cacheName = 'bramsmulders:4.1.3';
const cacheFiles = [
'/about/',
'/offline/',
'/blog/structured-frontend-components/',
'/blog/how-i-improved-my-workflow-with-smacss-sass/',
'/blog/finger-friendly-all-the-things/'
];
self.addEventListener('install', (event) => {
event.waitUntil(
caches
.open(cacheName)
.then((cache) => {
// console.log('Opened cache');
return cache.addAll(cacheFiles);
})
);
});
self.addEventListener('fetch', (event) => {
event.respondWith(
caches
.match(event.request)
.then((response) => {
// Grab the response from asset cache
if (response) {
return response;
}
return fetch(event.request);
})
.catch(() => {
// Network is offline, return the cached offline page
return caches.match('/offline/');
})
);
});
self.addEventListener('activate', (event) => {
const cacheWhitelist = ['bramsmulders:4.1.3'];
event.waitUntil(
caches.keys().then((cacheNames) => {
return Promise.all(
cacheNames.map((cacheName) => {
if (cacheWhitelist.indexOf(cacheName) === -1) {
return caches.delete(cacheName);
}
})
);
})
);
});
manifest.json
{
"short_name": "Bram Smulders",
"name": "Bram Smulders; UX and Front-end architecture enthousiast",
"start_url": "/",
"background_color": "#ffffff",
"theme_color": "#fc6471",
"display": "standalone",
"icons": [
{
"src": "\/android-icon-144x144.png",
"sizes": "144x144",
"type": "image\/png",
"density": "3.0"
}
]
}
window.addEventListener('beforeinstallprompt', function(e) {
// beforeinstallprompt Event fired
// e.userChoice will return a Promise.
e.userChoice.then(function(choiceResult) {
console.log(choiceResult.outcome);
if(choiceResult.outcome == 'dismissed') {
console.log('User cancelled home screen install');
} else {
console.log('User added to home screen');
}
});
});