-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathsw.js
More file actions
98 lines (89 loc) · 2.25 KB
/
Copy pathsw.js
File metadata and controls
98 lines (89 loc) · 2.25 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
95
96
97
98
const CACHE_NAME = "oh-card-studio-v18";
const APP_SHELL = "./index.html";
const CORE_ASSETS = [
"./",
"./index.html",
"./styles.css",
"./script.js",
"./manifest.webmanifest",
"./favicon.svg",
"./icon.svg",
"./data/oh-image-deck.json",
"./data/oh-word-deck.json"
];
self.addEventListener("install", (event) => {
event.waitUntil(
caches
.open(CACHE_NAME)
.then((cache) => cache.addAll(CORE_ASSETS))
.then(() => self.skipWaiting())
.catch(() => self.skipWaiting())
);
});
self.addEventListener("activate", (event) => {
event.waitUntil(
caches
.keys()
.then((keys) => Promise.all(keys.map((key) => (key === CACHE_NAME ? null : caches.delete(key)))))
.then(() => self.clients.claim())
);
});
self.addEventListener("message", (event) => {
if (event.data && event.data.type === "SKIP_WAITING") {
self.skipWaiting();
}
});
function isCacheableResponse(request, response) {
if (!response || !response.ok) {
return false;
}
try {
const requestUrl = new URL(request.url);
return requestUrl.origin === self.location.origin;
} catch (error) {
return false;
}
}
async function networkFirst(request, allowShellFallback) {
try {
const response = await fetch(request);
if (isCacheableResponse(request, response)) {
const cache = await caches.open(CACHE_NAME);
cache.put(request, response.clone());
} else if (!response.ok) {
const cached = await caches.match(request);
if (cached) {
return cached;
}
}
return response;
} catch (error) {
const cached = await caches.match(request);
if (cached) {
return cached;
}
if (allowShellFallback) {
const shell = await caches.match(APP_SHELL);
if (shell) {
return shell;
}
}
throw error;
}
}
self.addEventListener("fetch", (event) => {
if (event.request.method !== "GET") {
return;
}
let requestUrl;
try {
requestUrl = new URL(event.request.url);
} catch (error) {
return;
}
if (requestUrl.origin !== self.location.origin) {
return;
}
const isNavigation = event.request.mode === "navigate" || event.request.destination === "document";
event.respondWith(networkFirst(event.request, isNavigation));
});