explodorama / files / static / sw.js
sw.js
52d68b59 2026-10-24 Pavel Safronov | 1 | /** |
| 2 | * The service worker that makes the game installable and playable offline (user request, | |
| 3 | * 2026-10-23). Network first: online, every request goes to the network as usual (so a new | |
| 4 | * deploy is picked up at once) and a copy is kept; offline, the copy is used. Only this site's | |
| 5 | * own GET requests are touched. Registered by main.ts in the built game only. | |
| 6 | */ | |
| 7 | const CACHE = 'explodorama' | |
| 8 | ||
| 9 | self.addEventListener('install', () => self.skipWaiting()) | |
| 10 | self.addEventListener('activate', (e) => e.waitUntil(self.clients.claim())) | |
| 11 | ||
| 12 | self.addEventListener('fetch', (e) => { | |
| 13 | const request = e.request | |
| 14 | if (request.method !== 'GET' || new URL(request.url).origin !== self.location.origin) return | |
| 15 | e.respondWith( | |
| 16 | fetch(request) | |
| 17 | .then((response) => { | |
| 18 | if (response.ok) { | |
| 19 | const copy = response.clone() | |
| 20 | e.waitUntil(caches.open(CACHE).then((cache) => cache.put(request, copy))) | |
| 21 | } | |
| 22 | return response | |
| 23 | }) | |
| 24 | .catch(() => caches.match(request).then((cached) => cached ?? Response.error())), | |
| 25 | ) | |
| 26 | }) |