-
Notifications
You must be signed in to change notification settings - Fork 16
/
sw.js
64 lines (57 loc) · 1.49 KB
/
sw.js
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
/*globals self, async, caches, fetch */
"use strict";
const SITE_CACHE = "site-v13";
self.addEventListener("install", ev => {
ev.waitUntil(cacheIsPopulated());
});
async function cacheIsPopulated() {
const resources = [
"./",
"./images/[email protected]",
"./images/github.svg",
"./images/logo.png",
"./images/logo.svg",
"./images/twitter_white.svg",
"./images/w3c_white.svg",
"./js/lib/hyperhtml.js",
"./manifest.json",
"./styles/fonts/nexa/Nexa_Bold.otf",
"./styles/style.css",
"./data/active.json",
"./data/archived.json",
];
const cache = await caches.open(SITE_CACHE);
await cache.addAll(resources);
}
self.addEventListener("activate", async () => {
const keys = await caches.keys();
await keys.filter(key => key !== SITE_CACHE).map(key => caches.delete(key));
});
self.addEventListener("message", ({ data: { action } }) => {
switch (action) {
case "skipWaiting":
self.skipWaiting();
break;
}
});
self.addEventListener("fetch", ev => {
ev.respondWith(aCachedResponse(ev));
});
async function aCachedResponse(ev) {
const response = await caches.match(ev.request);
if (response) {
return response;
}
console.warn("No caches match for?:", ev.request.url);
// go to network instead
try {
const netResponse = await fetch(ev.request);
if (netResponse.ok) {
return netResponse;
}
} catch (err) {
// just return the index if all goes bad.
console.error(err);
}
return await caches.match("/");
}