Last active
April 27, 2020 22:58
-
-
Save DannyMoerkerke/effcac79e6c3ce34ffc332e655a138fb to your computer and use it in GitHub Desktop.
Bare bones service worker
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
// give your cache a name | |
const cacheName = 'my-cache'; | |
// put the static assets and routes you want to cache here | |
const filesToCache = [ | |
'/', | |
'/about', | |
'/index.html', | |
'/about.html', | |
'/css/styles.css', | |
'/js/app.js', | |
'/img/logo.png' | |
]; | |
// the event handler for the activate event | |
self.addEventListener('activate', e => self.clients.claim()); | |
// the event handler for the install event | |
// typically used to cache assets | |
self.addEventListener('install', e => { | |
e.waitUntil( | |
caches.open(cacheName) | |
.then(cache => cache.addAll(filesToCache)) | |
); | |
}); | |
// the fetch event handler, to intercept requests and serve all | |
// static assets from the cache | |
self.addEventListener('fetch', e => { | |
e.respondWith( | |
caches.match(e.request) | |
.then(response => response ? response : fetch(e.request)) | |
) | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment