diff options
Diffstat (limited to 'web/sw.js')
| -rw-r--r-- | web/sw.js | 24 |
1 files changed, 24 insertions, 0 deletions
diff --git a/web/sw.js b/web/sw.js new file mode 100644 index 0000000..8298b85 --- /dev/null +++ b/web/sw.js @@ -0,0 +1,24 @@ +// 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()))); +}); |
