self.addEventListener('install', (event) => {
console.log('--------install', event);
});
self.addEventListener('activate', (event) => {
console.log('----------activate', event);
});
self.addEventListener('message', (event) => {
console.log('----------message', event);
});
self.addEventListener('fetch', (event) => {
console.log('----------fetch', event);
event.respondWith(
fetch(event.request).catch(() => {
return caches.match(event.request);
}),
);
});
self.addEventListener('activate', event => {
event.waitUntil(self.clients.claim())
})
/*
* Caching
*/
const CACHE_NAME = 'v_17_' + __BUILD_TIME__
const precacheResources = [__BASE_PATH__, __BASE_PATH__ + '/']
self.addEventListener('install', event => {
event.waitUntil((async () => {
const cache = await caches.open(CACHE_NAME)
await cache.addAll(precacheResources)
self.skipWaiting()
})())
})
self.addEventListener('activate', async event => {
event.waitUntil(self.clients.claim())
self.registration.unregister()
// remove old cache from old versions of service worker
const cacheNames = await caches.keys()
await Promise.all(cacheNames.map(async cacheName => {
if (cacheName !== CACHE_NAME) await caches.delete(cacheName)
}))
})
self.addEventListener('fetch', async event => {
event.respondWith(
caches.match(event.request).then(cachedResponse => {
if (cachedResponse) return cachedResponse
return fetch(event.request).then(async response => {
if (event.request.method === 'GET' && event.request.url.startsWith('http') &&
!event.request.url.includes('/api/')) {
const cache = await caches.open(CACHE_NAME)
await cache.put(event.request, response.clone())
}
return response
})
})
)
})