Skip to content

Instantly share code, notes, and snippets.

@DannyMoerkerke
Last active April 27, 2020 22:58
Show Gist options
  • Save DannyMoerkerke/effcac79e6c3ce34ffc332e655a138fb to your computer and use it in GitHub Desktop.
Save DannyMoerkerke/effcac79e6c3ce34ffc332e655a138fb to your computer and use it in GitHub Desktop.
Bare bones service worker
// 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