25 lines
1.3 KiB
JavaScript
25 lines
1.3 KiB
JavaScript
// Keeps the app shell so the player opens with no connection. Audio is stored separately by the page (IndexedDB).
|
|
// Service workers only run on HTTPS (or localhost).
|
|
const CACHE = 'shell-v1';
|
|
const STATIC = ['/manifest.webmanifest', '/icon-180.png', '/icon-192.png', '/icon-512.png'];
|
|
|
|
self.addEventListener('install', e => {
|
|
e.waitUntil(caches.open(CACHE).then(c => Promise.all(['/', ...STATIC].map(u => c.add(u).catch(() => {})))).then(() => self.skipWaiting()));
|
|
});
|
|
self.addEventListener('activate', e => {
|
|
e.waitUntil(caches.keys().then(ks => Promise.all(ks.filter(k => k !== CACHE).map(k => caches.delete(k)))).then(() => self.clients.claim()));
|
|
});
|
|
self.addEventListener('fetch', e => {
|
|
const r = e.request, url = new URL(r.url);
|
|
if (r.method !== 'GET' || url.origin !== location.origin) return;
|
|
if (r.mode === 'navigate' && url.pathname === '/') {
|
|
// newest page when online, the saved one when not. Never save a sign-in redirect.
|
|
e.respondWith(fetch(r).then(res => {
|
|
if (res.ok && !res.redirected) { const copy = res.clone(); caches.open(CACHE).then(c => c.put('/', copy)); }
|
|
return res;
|
|
}).catch(() => caches.match('/')));
|
|
} else if (STATIC.includes(url.pathname)) {
|
|
e.respondWith(caches.match(r).then(hit => hit || fetch(r)));
|
|
}
|
|
});
|