Skip to content

Instantly share code, notes, and snippets.

@Legends
Last active November 2, 2019 21:57
Show Gist options
  • Select an option

  • Save Legends/b5144d8d125ba64c7b8c0a3b54ffa871 to your computer and use it in GitHub Desktop.

Select an option

Save Legends/b5144d8d125ba64c7b8c0a3b54ffa871 to your computer and use it in GitHub Desktop.
// ******************************************* Main.js ********************************************************
// Make sure sw are supported
if ('serviceWorker' in navigator) {
window.addEventListener('load', () => {
navigator.serviceWorker.register('../sw_cached_pages.js') // register the serviceWorker
.then(reg => console.log('Service Worker: Registered (Pages)'))
.catch(err => console.log(`Service Worker: Error: ${err}`));
});
}
// ******************************************* sw_cached_site.js ***********************************************
// What it does: it caches all requests a site makes (css, js, html, etc.) and when the app is offline it loads the cached version.
const cacheName = 'v2';
// Call Install Event
self.addEventListener('install', e => {
console.log('Service Worker: Installed');
});
// Call Activate Event
self.addEventListener('activate', e => {
console.log('Service Worker: Activated');
// Remove unwanted caches
e.waitUntil(
caches.keys().then(cacheNames => {
return Promise.all(
cacheNames.map(cache => {
if (cache !== cacheName) {
console.log('Service Worker: Clearing Old Cache');
return caches.delete(cache);
}
})
);
})
);
});
// Call Fetch Event
self.addEventListener('fetch', e => {
console.log('Service Worker: Fetching');
e.respondWith(
fetch(e.request)
.then(res => {
// Make copy/clone of response
const resClone = res.clone();
// Open cache
caches.open(cacheName).then(cache => {
// Add response to cache
cache.put(e.request, resClone);
});
return res;
})
.catch(err => caches.match(e.request).then(res => res))
);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment