41 lines
1.2 KiB
JavaScript
41 lines
1.2 KiB
JavaScript
const CACHE = 'faelle-v1';
|
|
const SHELL = ['/', '/manifest.webmanifest', '/icons/icon-192.png', '/icons/icon-512.png'];
|
|
|
|
self.addEventListener('install', (e) => {
|
|
e.waitUntil(caches.open(CACHE).then((c) => c.addAll(SHELL)).then(() => self.skipWaiting()));
|
|
});
|
|
|
|
self.addEventListener('activate', (e) => {
|
|
e.waitUntil(
|
|
caches.keys()
|
|
.then((keys) => Promise.all(keys.filter((k) => k !== CACHE).map((k) => caches.delete(k))))
|
|
.then(() => self.clients.claim())
|
|
);
|
|
});
|
|
|
|
self.addEventListener('fetch', (e) => {
|
|
const req = e.request;
|
|
if (req.method !== 'GET') return;
|
|
|
|
// Pages: network first so updates show up, cache as offline fallback.
|
|
if (req.mode === 'navigate') {
|
|
e.respondWith(
|
|
fetch(req)
|
|
.then((res) => { const copy = res.clone(); caches.open(CACHE).then((c) => c.put('/', copy)); return res; })
|
|
.catch(() => caches.match('/'))
|
|
);
|
|
return;
|
|
}
|
|
|
|
// Everything else (icons, Google Fonts): cache first, fill cache on miss.
|
|
e.respondWith(
|
|
caches.match(req).then((hit) => hit || fetch(req).then((res) => {
|
|
if (res.ok || res.type === 'opaque') {
|
|
const copy = res.clone();
|
|
caches.open(CACHE).then((c) => c.put(req, copy));
|
|
}
|
|
return res;
|
|
}))
|
|
);
|
|
});
|