Skip to content

Instantly share code, notes, and snippets.

@kaknut
Created June 5, 2019 10:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kaknut/902cd6fc70574b0123e10846ee25fb1f to your computer and use it in GitHub Desktop.
Save kaknut/902cd6fc70574b0123e10846ee25fb1f to your computer and use it in GitHub Desktop.
self.addEventListener('install', function(event){
event.waitUntil(
caches.open('NutPanda-cache-v10').then(function(cache){
return cache.addAll([ // add the links to assests you want to cache
'https://demo.com/main.css',
'https://example.co/min.css',
]);
})
);
});
//This is the "Offline page" service worker
// make sure to create a page called offline.html
//Install stage sets up the offline page in the cache and opens a new cache
self.addEventListener('install', function(event) {
var offlinePage = new Request('offline.html');
event.waitUntil(
fetch(offlinePage).then(function(response) {
return caches.open('offline-v4').then(function(cache) {
console.log(' Cached offline page during Install'+ response.url);
return cache.put(offlinePage, response);
});
}));
});
//If any fetch fails, it will show the offline page.
//Maybe this should be limited to HTML documents?
self.addEventListener('fetch', function(event) {
event.respondWith(
fetch(event.request).catch(function(error) {
console.error( 'Network request Failed. Serving offline page ' + error );
return caches.open('offline-v4').then(function(cache) {
return cache.match('offline.html');
});
}
));
});
//This is a event that can be fired from your page to tell the SW to update the offline page
self.addEventListener('refreshOffline', function(response) {
return caches.open('offline-v4').then(function(cache) {
console.log('Offline page updated from refreshOffline event: '+ response.url);
return cache.put(offlinePage, response);
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment