Repository navigation
Expand file tree
/
Copy pathsw.js
More file actions
66 lines (61 loc) · 1.68 KB
/
Copy pathsw.js
File metadata and controls
66 lines (61 loc) · 1.68 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
// Minimal service worker: cache-first for the app shell, offline fallback to cached index.html.
const CACHE_NAME = "coach-cache-v1";
const APP_SHELL = [
"./index.html",
"./data.js",
"./manifest.webmanifest"
];
self.addEventListener("install", (event) => {
event.waitUntil(
caches.open(CACHE_NAME).then((cache) => cache.addAll(APP_SHELL))
);
self.skipWaiting();
});
self.addEventListener("activate", (event) => {
event.waitUntil(
caches.keys().then((names) =>
Promise.all(
names
.filter((name) => name !== CACHE_NAME)
.map((name) => caches.delete(name))
)
)
);
self.clients.claim();
});
self.addEventListener("fetch", (event) => {
const req = event.request;
if (req.method !== "GET") return;
event.respondWith(
caches.match(req).then((cached) => {
if (cached) {
// Serve from cache immediately, refresh in the background.
event.waitUntil(
fetch(req)
.then((res) => {
if (res && res.ok) {
caches.open(CACHE_NAME).then((cache) => cache.put(req, res.clone()));
}
})
.catch(() => {})
);
return cached;
}
return fetch(req)
.then((res) => {
if (res && res.ok) {
const clone = res.clone();
caches.open(CACHE_NAME).then((cache) => cache.put(req, clone));
}
return res;
})
.catch(() => {
// Offline fallback: serve the cached shell for navigations.
if (req.mode === "navigate") {
return caches.match("./index.html");
}
return caches.match(req);
});
})
);
});