From fbfd66f18fca3a3d5cf46001eaf1661bd63bbf6d Mon Sep 17 00:00:00 2001 From: David Vazgenovich Shakaryan Date: Thu, 12 May 2022 17:12:21 -0700 Subject: web: support installing as progressive web app™ MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- web/static/sw.js | 68 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 68 insertions(+) create mode 100644 web/static/sw.js (limited to 'web/static/sw.js') diff --git a/web/static/sw.js b/web/static/sw.js new file mode 100644 index 0000000..3a92eb3 --- /dev/null +++ b/web/static/sw.js @@ -0,0 +1,68 @@ +const CACHE_PREFIX = 'dartboat-' +const CACHE_VERSION = '1'; +const CACHE_NAME = `${CACHE_PREFIX}${CACHE_VERSION}`; + +const FILES = [ + './', + 'dartboat.js', + 'dartboat_wasm.js', + 'dartboat_wasm.wasm', + 'style.css', + 'icons.woff2', + 'inter-num.woff2', + 'dartboat_16.png', + 'dartboat_32.png', + 'dartboat_64.png', + 'dartboat_96.png', + 'dartboat_128.png', + 'dartboat_192.png', + 'dartboat_256.png', + 'dartboat_512.png' +] + +function swlog(str) { + console.log(`[service worker] ${str}`); +} + +self.addEventListener('install', e => { + swlog('installing'); + + e.waitUntil((async() => { + swlog(`initialising cache ${CACHE_NAME}`); + const cache = await caches.open(CACHE_NAME); + await cache.addAll(FILES); + })()); + + swlog('installed'); +}); + +self.addEventListener('activate', e => { + e.waitUntil(caches.keys().then((keys) => { + return Promise.all(keys.map((k) => { + if (k === CACHE_NAME || !k.startsWith(CACHE_PREFIX)) + return; + + swlog(`deleting cache ${k}`); + return caches.delete(k); + })); + })); +}); + +self.addEventListener('fetch', e => { + e.respondWith((async () => { + const cache = await caches.open(CACHE_NAME); + + const cached = await cache.match(e.request); + swlog(`${cached ? 'hit' : 'miss'} ${e.request.url}`); + if (cached) + return cached; + + if (!(resp = await fetch(e.request)).ok) { + swlog(`ignore status:${resp.status} ${e.request.url}`); + } else { + swlog(`put ${e.request.url}`); + cache.put(e.request, resp.clone()); + } + return resp; + })()); +}); -- cgit v1.2.3-70-g09d2