-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsw.js
More file actions
61 lines (56 loc) · 1.56 KB
/
sw.js
File metadata and controls
61 lines (56 loc) · 1.56 KB
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
/* ─── Service Worker · Chomp Snake PWA ─── */
const CACHE_NAME = 'chomp-snake-v1';
const ASSETS = [
'/',
'/index.html',
'/manifest.json',
'/styles/main.css',
'/js/constants.js',
'/js/security.js',
'/js/audio.js',
'/js/ranks.js',
'/js/dashboard.js',
'/js/game.js',
'/js/main.js',
'/icons/icon-192.svg',
'/icons/icon-512.svg'
];
/* ── Install: pre-cache all static assets ── */
self.addEventListener('install', e => {
e.waitUntil(
caches.open(CACHE_NAME)
.then(cache => cache.addAll(ASSETS))
.then(() => self.skipWaiting())
);
});
/* ── Activate: purge old caches ── */
self.addEventListener('activate', e => {
e.waitUntil(
caches.keys().then(keys =>
Promise.all(keys
.filter(k => k !== CACHE_NAME)
.map(k => caches.delete(k))
)
).then(() => self.clients.claim())
);
});
/* ── Fetch: cache-first, fallback to network ── */
self.addEventListener('fetch', e => {
// Only handle GET requests
if (e.request.method !== 'GET') return;
e.respondWith(
caches.match(e.request).then(cached => {
if (cached) return cached;
return fetch(e.request).then(response => {
// Don't cache bad responses
if (!response || response.status !== 200 || response.type !== 'basic') {
return response;
}
// Clone and cache
const toCache = response.clone();
caches.open(CACHE_NAME).then(cache => cache.put(e.request, toCache));
return response;
});
}).catch(() => caches.match('/index.html'))
);
});