Repository navigation
Expand file tree
/
Copy pathservice-worker.js
More file actions
58 lines (53 loc) · 1.72 KB
/
Copy pathservice-worker.js
File metadata and controls
58 lines (53 loc) · 1.72 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
const CACHE_NAME = "taskkar-shell-v7";
const OLD_CACHE_PREFIXES = ["daymark-shell-", "taskkar-shell-"];
const SHELL_FILES = [
"./",
"./index.html",
"./styles.css",
"./app.js",
"./manifest.webmanifest",
"./icons/favicon.svg",
"./icons/icon-192.svg",
"./icons/icon-512.svg",
"./fonts/roboto_serif.ttf",
"./fonts/OFL-RobotoSerif.txt",
];
self.addEventListener("install", (event) => {
event.waitUntil(
caches.open(CACHE_NAME).then((cache) => cache.addAll(SHELL_FILES)).then(() => self.skipWaiting()),
);
});
self.addEventListener("activate", (event) => {
event.waitUntil(
caches.keys()
.then((names) => Promise.all(names.filter((name) => OLD_CACHE_PREFIXES.some((prefix) => name.startsWith(prefix)) && name !== CACHE_NAME)
.map((name) => caches.delete(name))))
.then(() => self.clients.claim()),
);
});
self.addEventListener("fetch", (event) => {
const { request } = event;
if (request.method !== "GET" || new URL(request.url).origin !== self.location.origin) return;
if (request.mode === "navigate") {
event.respondWith(
fetch(request).catch(async () => {
const cachedPage = await caches.match("./index.html");
if (cachedPage) return cachedPage;
throw new Error("The offline app shell has not been cached yet.");
}),
);
return;
}
event.respondWith(
caches.match(request).then((cached) => {
const fresh = fetch(request).then((response) => {
if (response.ok) {
const copy = response.clone();
caches.open(CACHE_NAME).then((cache) => cache.put(request, copy));
}
return response;
});
return cached || fresh;
}),
);
});