Last active
April 3, 2021 05:30
-
-
Save markwylde/a5ffc658a16257bf644bed6fdfab0464 to your computer and use it in GitHub Desktop.
Service worker to cache everything
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
// 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 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
// 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