76 lines
2.0 KiB
JavaScript
76 lines
2.0 KiB
JavaScript
const CACHE_NAME = 'lonc-shell-v2';
|
|
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;
|
|
}
|
|
|
|
const destination = event.request.destination;
|
|
if (
|
|
destination === 'script' ||
|
|
destination === 'style' ||
|
|
destination === 'worker' ||
|
|
requestUrl.pathname.endsWith('.js') ||
|
|
requestUrl.pathname.endsWith('.css')
|
|
) {
|
|
event.respondWith(
|
|
fetch(event.request)
|
|
.then((networkResponse) => {
|
|
const clone = networkResponse.clone();
|
|
caches.open(CACHE_NAME).then((cache) => cache.put(event.request, clone));
|
|
return networkResponse;
|
|
})
|
|
.catch(() => caches.match(event.request)),
|
|
);
|
|
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;
|
|
})
|
|
);
|
|
}),
|
|
);
|
|
});
|