56 lines
1.4 KiB
JavaScript
56 lines
1.4 KiB
JavaScript
|
|
const CACHE_NAME = 'lonc-shell-v1';
|
||
|
|
const APP_SHELL = ['/', '/index.html', '/manifest.webmanifest', '/offline.html', '/icons/icon.svg', '/icons/icon-mask.svg'];
|
||
|
|
|
||
|
|
self.addEventListener('install', (event) => {
|
||
|
|
event.waitUntil(caches.open(CACHE_NAME).then((cache) => cache.addAll(APP_SHELL)));
|
||
|
|
self.skipWaiting();
|
||
|
|
});
|
||
|
|
|
||
|
|
self.addEventListener('activate', (event) => {
|
||
|
|
event.waitUntil(
|
||
|
|
caches.keys().then((keys) =>
|
||
|
|
Promise.all(
|
||
|
|
keys
|
||
|
|
.filter((key) => key !== CACHE_NAME)
|
||
|
|
.map((key) => caches.delete(key)),
|
||
|
|
),
|
||
|
|
),
|
||
|
|
);
|
||
|
|
self.clients.claim();
|
||
|
|
});
|
||
|
|
|
||
|
|
self.addEventListener('fetch', (event) => {
|
||
|
|
if (event.request.method !== 'GET') {
|
||
|
|
return;
|
||
|
|
}
|
||
|
|
|
||
|
|
const requestUrl = new URL(event.request.url);
|
||
|
|
|
||
|
|
if (requestUrl.origin !== self.location.origin) {
|
||
|
|
return;
|
||
|
|
}
|
||
|
|
|
||
|
|
if (event.request.mode === 'navigate') {
|
||
|
|
event.respondWith(
|
||
|
|
fetch(event.request).catch(async () => {
|
||
|
|
const shell = await caches.match('/index.html');
|
||
|
|
return shell || caches.match('/offline.html');
|
||
|
|
}),
|
||
|
|
);
|
||
|
|
return;
|
||
|
|
}
|
||
|
|
|
||
|
|
event.respondWith(
|
||
|
|
caches.match(event.request).then((response) => {
|
||
|
|
return (
|
||
|
|
response ||
|
||
|
|
fetch(event.request).then((networkResponse) => {
|
||
|
|
const clone = networkResponse.clone();
|
||
|
|
caches.open(CACHE_NAME).then((cache) => cache.put(event.request, clone));
|
||
|
|
return networkResponse;
|
||
|
|
})
|
||
|
|
);
|
||
|
|
}),
|
||
|
|
);
|
||
|
|
});
|