-
-
Save aliams/641ea0aef7b8661da1b2336405aa0e4d to your computer and use it in GitHub Desktop.
Simple service worker example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<script> | |
navigator.serviceWorker.register('sw.js', {scope: '/'}) | |
.then( | |
function (registration) { | |
console.log('Service worker registered!'); | |
}, | |
function (err) { | |
console.error('Installation failed!', err); | |
} | |
); | |
</script> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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