Skip to content

Instantly share code, notes, and snippets.

@aliams
Last active May 8, 2018 03:17
Show Gist options
  • Save aliams/641ea0aef7b8661da1b2336405aa0e4d to your computer and use it in GitHub Desktop.
Save aliams/641ea0aef7b8661da1b2336405aa0e4d to your computer and use it in GitHub Desktop.
Simple service worker example
<script>
navigator.serviceWorker.register('sw.js', {scope: '/'})
.then(
function (registration) {
console.log('Service worker registered!');
},
function (err) {
console.error('Installation failed!', err);
}
);
</script>
self.oninstall = function(event) {
event.waitUntil(
caches.open('assets-v1').then(function(cache) {
return cache.addAll([
'/',
'/index.html',
'/styles.css',
'/bg.jpg',
'/fallback.html'
]);
})
);
}
self.onactivate = function(event) {
var keepList = ['assets-v1'];
event.waitUntil(
caches.keys().then(function(cacheNameList) {
return Promise.all(cacheNameList.map(function(cacheName) {
if (keepList.indexOf(cacheName) === -1) {
return caches.delete(cacheName);
}
}));
})
);
}
self.onfetch = function(event) {
event.respondWith(
caches.match(event.request).then(function(response) {
return response || fetch(event.request).catch(function() {
return caches.match('/fallback.html');
});
})
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment