-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathworker.js
More file actions
73 lines (67 loc) · 1.94 KB
/
worker.js
File metadata and controls
73 lines (67 loc) · 1.94 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
const version = "v1.3.1";
const addResourcesToCache = async (resources) => {
const cache = await caches.open(version);
console.log("Adding resources to cache:", resources.join(", "));
await cache.addAll(resources);
};
const putInCache = async (request, response) => {
const cache = await caches.open(version);
await cache.put(request, response);
};
const networkFirst = async ({ request, fallbackUrl }) => {
// First, try to get the resource from the network.
try {
const responseFromNetwork = await fetch(request);
// If the network request succeeded, clone the response:
// - put one copy in the cache, for the next time
// - return the original to the app
// Cloning is needed because a response can only be consumed once.
putInCache(request, responseFromNetwork.clone());
return responseFromNetwork;
} catch (error) {
const responseFromCache = await caches.match(request);
if (responseFromCache) {
return responseFromCache;
}
const fallbackResponse = await caches.match(fallbackUrl);
if (fallbackResponse) {
return fallbackResponse;
}
// When even the fallback response is not available,
// there is nothing we can do, but we must always
// return a Response object.
return new Response("Network error happened", {
status: 408,
headers: { "Content-Type": "text/plain" },
});
}
};
self.addEventListener("fetch", (event) => {
event.respondWith(
networkFirst({
request: event.request,
fallbackUrl: "/fallback.html",
}),
);
});
self.addEventListener("install", (event) => {
event.waitUntil(
addResourcesToCache([
"/",
"/index.html",
"/index.css",
"/css/webfonts_Chess/Chess.ttf.woff",
"/css/webfonts_Chess/Chess.ttf.svg#Chess",
"/css/webfonts_Chess/Chess.ttf.eot",
"/css/webfonts_Chess/Chess.ttf.eot?#iefix",
"/css/hex.css",
"/css/print.css",
"/js/black.js",
"/js/board.js",
"/js/constants.js",
"/js/play.js",
"/js/register.js",
"/js/white.js",
]),
);
});