Repository navigation
Expand file tree
/
Copy pathsw.js
More file actions
94 lines (85 loc) · 2.54 KB
/
Copy pathsw.js
File metadata and controls
94 lines (85 loc) · 2.54 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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
const CACHE_NAME = 'macro-tracker-2026-10-08.1';
const APP_VERSION = '2026-10-08.1';
const STATIC_ASSETS = [
'/',
'/index.html',
'/manifest.json',
'/icon-192.svg',
'/icon-512.svg'
];
self.addEventListener('install', e => {
e.waitUntil(
caches.open(CACHE_NAME).then(cache => cache.addAll(STATIC_ASSETS))
);
self.skipWaiting(); // activate immediately, don't wait for tabs to close
});
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()) // take control of all open pages
);
});
self.addEventListener('fetch', e => {
const url = new URL(e.request.url);
// Never intercept docs pages — let them load fresh from the network
if (url.pathname.startsWith('/docs/')) {
return;
}
// Network-first for Open Food Facts API and USDA
if (url.hostname.includes('api.nal.usda.gov')) {
e.respondWith(
fetch(e.request)
.then(res => {
const clone = res.clone();
caches.open(CACHE_NAME).then(cache => cache.put(e.request, clone));
return res;
})
.catch(() => caches.match(e.request))
);
return;
}
if (url.hostname.includes('openfoodfacts.org')) { // covers en., uk., world., etc.
e.respondWith(
fetch(e.request)
.then(res => {
const clone = res.clone();
caches.open(CACHE_NAME).then(cache => cache.put(e.request, clone));
return res;
})
.catch(() => caches.match(e.request))
);
return;
}
// Cache-first for ZXing CDN
if (url.hostname === 'unpkg.com') {
e.respondWith(
caches.match(e.request).then(cached => {
if (cached) return cached;
return fetch(e.request).then(res => {
const clone = res.clone();
caches.open(CACHE_NAME).then(cache => cache.put(e.request, clone));
return res;
});
})
);
return;
}
// Network-first for the main HTML so updates are always picked up
if (url.pathname.endsWith('/') || url.pathname.endsWith('index.html')) {
e.respondWith(
fetch(e.request)
.then(res => {
const clone = res.clone();
caches.open(CACHE_NAME).then(cache => cache.put(e.request, clone));
return res;
})
.catch(() => caches.match(e.request))
);
return;
}
// Cache-first for everything else (icons, manifest)
e.respondWith(
caches.match(e.request).then(cached => cached || fetch(e.request))
);
});