// sketchbook's service worker, for sketches built as installable apps: it // keeps a copy of everything the page fetches, so the app opens offline. // Network first, so a new build shows as soon as there is a network; the // copy only when there is none. const cache = `sketchbook ${self.registration.scope}`; const core = ['./', 'index.html', 'host.js', 'sketch.wasm', 'manifest.webmanifest']; self.addEventListener('install', event => { event.waitUntil(caches.open(cache).then(c => Promise.all(core.map(url => c.add(url).catch(() => {}))))); self.skipWaiting(); }); self.addEventListener('activate', event => event.waitUntil(self.clients.claim())); self.addEventListener('fetch', event => { const request = event.request; if (request.method !== 'GET' || !request.url.startsWith(self.registration.scope)) return; event.respondWith(fetch(request).then(response => { if (response.ok) { const copy = response.clone(); event.waitUntil(caches.open(cache).then(c => c.put(request, copy))); } return response; }, () => caches.open(cache).then(c => c.match(request, {ignoreSearch: true})).then(found => found ?? Response.error()))); });