Created
August 2, 2018 20:50
-
-
Save bradtraversy/15f71490d7ae98e4326a5217b07fba1a to your computer and use it in GitHub Desktop.
Service worker to cache pages
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
const cacheName = 'v1'; | |
const cacheAssets = [ | |
'index.html', | |
'about.html', | |
'/css/style.css', | |
'/js/main.js' | |
]; | |
// Call Install Event | |
self.addEventListener('install', e => { | |
console.log('Service Worker: Installed'); | |
e.waitUntil( | |
caches | |
.open(cacheName) | |
.then(cache => { | |
console.log('Service Worker: Caching Files'); | |
cache.addAll(cacheAssets); | |
}) | |
.then(() => self.skipWaiting()) | |
); | |
}); | |
// 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).catch(() => caches.match(e.request))); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment