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.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('message', (event) => { if (event?.data?.type === 'SKIP_WAITING') { self.skipWaiting(); } }); 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; } if (requestUrl.pathname === '/version.json') { event.respondWith(fetch(event.request, { cache: 'no-store' })); 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; }) ); }), ); });