Skip to content

Instantly share code, notes, and snippets.

@vipinkrishna
Forked from bradtraversy/sw_cached_site.js
Created August 19, 2021 07:54
Show Gist options
  • Save vipinkrishna/3d16ac928e631f62fb9f56413ee2e4de to your computer and use it in GitHub Desktop.
Save vipinkrishna/3d16ac928e631f62fb9f56413ee2e4de to your computer and use it in GitHub Desktop.
Service Worker To Cache Response
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 cahce
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