service-worker.js (1.2 KB)


 1 // Keeps an installed copy of soundstone working when the server it came from
 2 // cannot be reached, which is the usual case for an install from a local network.
 3 
 4 const CACHE_NAME = 'soundstone';
 5 const FILES = ['./', 'resources/style.css', 'resources/main.js', 'resources/deck.js', 'manifest.json', 'resources/favicon.svg', 'resources/icon.png'];
 6 
 7 self.addEventListener('install', event => {
 8 	self.skipWaiting();
 9 	event.waitUntil(caches.open(CACHE_NAME).then(cache => cache.addAll(FILES)));
10 });
11 
12 self.addEventListener('activate', event => {
13 	event.waitUntil(self.clients.claim());
14 });
15 
16 // Answers from the cache immediately, and refreshes the cache from the network in
17 // the background. A change on the server therefore shows up on the second launch.
18 self.addEventListener('fetch', event => {
19 	if (event.request.method !== 'GET') return;
20 	event.respondWith(caches.open(CACHE_NAME).then(async cache => {
21 		const cached = await cache.match(event.request);
22 		const fresh = fetch(event.request).then(response => {
23 			if (response.ok) cache.put(event.request, response.clone());
24 			return response;
25 		});
26 		if (!cached) return fresh;
27 		event.waitUntil(fresh.catch(() => {}));
28 		return cached;
29 	}));
30 });