summaryrefslogtreecommitdiff
path: root/web/sw.js
blob: 8298b85e800051f574380d484c6d369ce795f6be (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
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())));
});