Skip to content

Instantly share code, notes, and snippets.

@markwylde
Last active April 3, 2021 05:30
Show Gist options
  • Save markwylde/a5ffc658a16257bf644bed6fdfab0464 to your computer and use it in GitHub Desktop.
Save markwylde/a5ffc658a16257bf644bed6fdfab0464 to your computer and use it in GitHub Desktop.
Service worker to cache everything
// This code should be accessable from your root domain
// As in, don't bundle
const cacheName = 'cache-v1';
// The activate handler takes care of cleaning up old caches.
self.addEventListener('activate', event => {
const currentCaches = [cacheName];
event.waitUntil(
caches.keys().then(cacheNames => {
return cacheNames.filter(cacheName => !currentCaches.includes(cacheName));
}).then(cachesToDelete => {
return Promise.all(cachesToDelete.map(cacheToDelete => {
return caches.delete(cacheToDelete);
}));
}).then(() => self.clients.claim())
);
});
self.addEventListener('fetch', function (event) {
event.respondWith(
caches.match(event.request).then(function (response) {
if (response) {
return response;
}
return fetch(event.request).then(async response => {
const cache = await caches.open(cacheName);
return cache.put(event.request, response.clone()).then(() => {
return response;
});
});
})
);
});
// This code should be called from within your bundled app.
if ('serviceWorker' in navigator) {
navigator.serviceWorker.register('/cacheWorker.js', {})
.then((registration) => {
registration.onupdatefound = () => {
window.location.reload();
};
console.log('Cache Worker - Registration succeeded');
}).catch((error) => {
console.log('Cache Worker - Registration failed', error);
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment