-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathservice-worker.js
More file actions
87 lines (80 loc) · 2.48 KB
/
Copy pathservice-worker.js
File metadata and controls
87 lines (80 loc) · 2.48 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
const CACHE_NAME = "plasticdetect-v9";
const ASSETS = [
"./",
"./index.html",
"./css/styles.css",
"./js/i18n.js",
"./js/data.js",
"./js/classifier.js",
"./js/recyclingLocator.js",
"./js/app.js",
"./img/resin-code-example.png",
"./js/model/model.json",
"./js/model/weights.bin",
"./js/model/class_map.json",
"./manifest.json",
"https://cdn.jsdelivr.net/npm/@tensorflow/tfjs@4.22.0/dist/tf.min.js",
"https://unpkg.com/leaflet@1.9.4/dist/leaflet.css",
"https://unpkg.com/leaflet@1.9.4/dist/leaflet.js"
];
// Live-data hosts for the Nearby Recycling locator: always prefer a fresh
// network response (centers/geocoding/map tiles change or get added), but
// fall back to whatever was last cached when offline or when every
// Overpass mirror is unreachable — recyclingLocator.js also keeps its own
// longer-lived localStorage cache on top of this.
const NETWORK_FIRST_HOSTS = [
"overpass-api.de",
"overpass.kumi.systems",
"overpass.openstreetmap.ru",
"nominatim.openstreetmap.org",
"tile.openstreetmap.org"
];
self.addEventListener("install", (event) => {
event.waitUntil(
caches.open(CACHE_NAME).then((cache) =>
Promise.all(ASSETS.map((url) => cache.add(url).catch(() => {})))
)
);
self.skipWaiting();
});
self.addEventListener("activate", (event) => {
event.waitUntil(
caches.keys().then((keys) =>
Promise.all(keys.filter((k) => k !== CACHE_NAME).map((k) => caches.delete(k)))
)
);
self.clients.claim();
});
function isNetworkFirstHost(url) {
try {
const hostname = new URL(url).hostname;
return NETWORK_FIRST_HOSTS.some((h) => hostname === h || hostname.endsWith("." + h));
} catch {
return false;
}
}
function networkFirst(event) {
return fetch(event.request)
.then((response) => {
const copy = response.clone();
caches.open(CACHE_NAME).then((cache) => cache.put(event.request, copy));
return response;
})
.catch(() => caches.match(event.request));
}
function cacheFirst(event) {
return caches.match(event.request).then((cached) => {
if (cached) return cached;
return fetch(event.request).then((response) => {
const copy = response.clone();
caches.open(CACHE_NAME).then((cache) => cache.put(event.request, copy));
return response;
}).catch(() => cached);
});
}
self.addEventListener("fetch", (event) => {
if (event.request.method !== "GET") return;
event.respondWith(
isNetworkFirstHost(event.request.url) ? networkFirst(event) : cacheFirst(event)
);
});