Skip to content

Instantly share code, notes, and snippets.

@timwright12
Last active May 5, 2024 21:04
Show Gist options
  • Save timwright12/23fad524b3a9605a8ae9 to your computer and use it in GitHub Desktop.
Save timwright12/23fad524b3a9605a8ae9 to your computer and use it in GitHub Desktop.
/*
// Source: https://madebymike.com.au//writing/service-workers/
<script>
if ( 'serviceWorker' in navigator && ( typeof Cache !== 'undefined' && Cache.prototype.addAll ) ) {
navigator.serviceWorker.register( '/sw.js' );
}
</script>
*/
// we'll version our cache (and learn how to delete caches in
// some other post)
const cacheName = 'v1::static';
self.addEventListener('install', e => {
// once the SW is installed, go ahead and fetch the resources
// to make this work offline
e.waitUntil(
caches.open(cacheName).then(cache => {
return cache.addAll([
'/',
/*
DEAR READER,
ADD A LIST OF YOUR ASSETS THAT
YOU WANT TO WORK WHEN OFFLINE
TO THIS ARRAY OF URLS
*/
]).then(() => self.skipWaiting());
})
);
});
// when the browser fetches a url, either response with
// the cached object or go ahead and fetch the actual url
self.addEventListener('fetch', event => {
event.respondWith(
caches.match(event.request).then(res => res || fetch(event.request))
);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment