24 lines
1.4 KiB
JavaScript
24 lines
1.4 KiB
JavaScript
/* Cache only the public, versioned application shell. API responses are never cached. */
|
|
const CACHE = 'airdef-shell-v7';
|
|
const FILES = ['index.html', 'app.css', 'app.js', 'map.js', 'manifest.webmanifest', 'icons/icon-192.png', 'icons/icon-512.png'];
|
|
const scope = new URL(self.registration.scope);
|
|
const shellUrls = FILES.map(path => new URL(path, scope).href);
|
|
|
|
self.addEventListener('install', event => {
|
|
event.waitUntil(caches.open(CACHE).then(cache => cache.addAll(shellUrls)).then(() => self.skipWaiting()));
|
|
});
|
|
self.addEventListener('activate', event => {
|
|
event.waitUntil(caches.keys().then(keys => Promise.all(keys.filter(key => key.startsWith('airdef-shell-') && key !== CACHE).map(key => caches.delete(key)))).then(() => self.clients.claim()));
|
|
});
|
|
self.addEventListener('fetch', event => {
|
|
const request = event.request;
|
|
const url = new URL(request.url);
|
|
if (request.method !== 'GET' || url.origin !== scope.origin || url.search ||
|
|
!url.pathname.startsWith(scope.pathname) || /(^|\/)api(?:\/|$)/.test(url.pathname)) return;
|
|
if (request.mode === 'navigate' && (url.pathname === scope.pathname || url.pathname === new URL('index.html', scope).pathname)) {
|
|
event.respondWith(caches.match(new URL('index.html', scope).href).then(cached => cached || fetch(request)));
|
|
} else if (shellUrls.includes(url.href)) {
|
|
event.respondWith(caches.match(request).then(cached => cached || fetch(request)));
|
|
}
|
|
});
|