Skip to content

Instantly share code, notes, and snippets.

@anurag-majumdar
Last active September 2, 2018 14:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save anurag-majumdar/273f19513eaf1aeb8e83c59db3b48373 to your computer and use it in GitHub Desktop.
Save anurag-majumdar/273f19513eaf1aeb8e83c59db3b48373 to your computer and use it in GitHub Desktop.
const staticCacheName = 'app-shell-static-v1';
const staticCacheFileNames = [
'public/offline.html',
'lib/app.js'
];
self.addEventListener('install', (event) => {
self.skipWaiting();
event.waitUntil(
caches.open(staticCacheName)
.then((cache) => {
cache.addAll([
'/',
'manifest.json',
...staticCacheFileNames
]);
})
.catch((error) => {
console.log(`Error caching static assets: ${error}`);
})
);
});
self.addEventListener('activate', (event) => {
if (self.clients && clients.claim) {
clients.claim();
}
event.waitUntil(
caches.keys().then((cacheNames) => {
return Promise.all(
cacheNames.filter((cacheName) => {
return cacheName.startsWith('app-shell-') && cacheName !== staticCacheName;
})
.map((cacheName) => {
return caches.delete(cacheName);
})
).catch((error) => {
console.log(`Some error occurred while removing existing cache: ${error}`);
});
}).catch((error) => {
console.log(`Some error occurred while removing existing cache: ${error}`);
}));
});
self.addEventListener('fetch', (event) => {
event.respondWith(
caches.match(event.request).then((response) => {
return response || fetch(event.request)
}).catch((error) => {
console.log(`Some error occurred while saving data to dynamic cache: ${error}`);
})
);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment