-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsw.js
More file actions
93 lines (81 loc) · 2.56 KB
/
sw.js
File metadata and controls
93 lines (81 loc) · 2.56 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
const CACHE = "hyperloop-v10";
const PAGES = [
"./", "./index.html", "./subteams.html", "./members.html",
"./apply.html", "./sponsors.html",
"./subteam-views/subteam-structures.html",
"./subteam-views/subteam-braking.html",
"./subteam-views/subteam-ecc.html",
"./subteam-views/subteam-magnetic.html",
"./subteam-views/subteam-power.html",
"./subteam-views/subteam-business.html",
"./shared.js", "./res/members.json"
];
self.addEventListener("install", e => {
e.waitUntil(self.skipWaiting());
});
self.addEventListener("activate", e => {
e.waitUntil(
caches.keys().then(keys =>
Promise.all(keys.filter(k => k !== CACHE).map(k => caches.delete(k)))
).then(() => self.clients.claim())
);
});
self.addEventListener("fetch", e => {
if (e.request.method !== "GET") return;
let url;
try {
url = new URL(e.request.url);
} catch {
return;
}
if (url.protocol !== "http:" && url.protocol !== "https:") return;
const isVideoAsset = url.pathname.endsWith(".mp4") || url.pathname.endsWith(".webm") || url.pathname.endsWith(".mov");
const networkFirstAsset = url.pathname.endsWith("/shared.js") || url.pathname.endsWith("/res/tw.css");
if (isVideoAsset || e.request.headers.has("range")) {
e.respondWith(fetch(e.request));
return;
}
e.respondWith(
caches.open(CACHE).then(async cache => {
if (e.request.mode === "navigate" || networkFirstAsset) {
try {
const fresh = await fetch(e.request);
if (fresh.ok) await cache.put(e.request, fresh.clone());
return fresh;
} catch (err) {
const cached = await cache.match(e.request);
if (cached) return cached;
throw err;
}
}
const cached = await cache.match(e.request);
if (cached) {
fetch(e.request).then(res => {
if (res.ok) {
cache.put(e.request, res.clone()).catch(() => {});
}
}).catch(() => {});
return cached;
}
const fresh = await fetch(e.request);
if (fresh.ok) await cache.put(e.request, fresh.clone());
return fresh;
})
);
});
self.addEventListener("message", e => {
if (e.data !== "prefetch") return;
e.waitUntil((async () => {
const cache = await caches.open(CACHE);
await Promise.all(PAGES.map(async url => {
const hit = await cache.match(url);
if (hit) return;
try {
const res = await fetch(url);
if (res.ok) await cache.put(url, res);
} catch {
// Ignore prefetch failures; the normal fetch path can retry.
}
}));
})());
});