summaryrefslogtreecommitdiff
path: root/web/static/sw.js
blob: f09f5fc82fa99f2e5eba9086260c7bef10effcec (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
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
const CACHE_PREFIX = 'dartboat-'
const CACHE_VERSION = '24';
const CACHE_NAME = `${CACHE_PREFIX}${CACHE_VERSION}`;

const CACHE_FILES = [
	'./',
	'style.css',
	'dartboat.js',
	'dartboat_wasm.js',
	'dartboat_wasm.wasm',
	'icons/dartboat_48.png',
	'fonts/Lato-Regular.woff2',
	'fonts/Lato-Bold.woff2',
	'fonts/SourceSerif4-Regular.ttf.woff2',
	'fonts/SourceSerif4-It.ttf.woff2',
	'fonts/SourceSerif4-Bold.ttf.woff2',
	'fonts/Inter-num.woff2',
	'fonts/bootstrap-icons-sub.woff2'
]

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(CACHE_FILES);
	})());
});

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;

		const resp = await fetch(e.request);
		if (!resp.ok) {
			swlog(`ignore status:${resp.status} ${e.request.url}`);
		} else {
			swlog(`put ${e.request.url}`);
			cache.put(e.request, resp.clone());
		}
		return resp;
	})());
});