-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathservice-worker.js
81 lines (73 loc) · 2.16 KB
/
service-worker.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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
const FILES_TO_CACHE = [
"./",
"./favicon.ico",
"./manifest.json",
"./browserconfig.xml",
"./index.html",
"./styles/main.min.css",
// "./dist/main.js",
"./scripts/main.js",
"./scripts/canvasOperations.js",
"./scripts/paletteOperations.js",
"./scripts/palettes.js",
"./scripts/smUtils.js",
"./scripts/utils.js"
];
const EMERALD_VERSION = "v0117";
const CACHE_NAME = "emeraldCache_v0117";
const cacheWhitelist = [CACHE_NAME];
self.addEventListener("install", event => {
self.skipWaiting();
event.waitUntil(
caches
.open(CACHE_NAME)
.then(cache => {
console.log("[ServiceWorker] Pre-caching offline page");
return cache.addAll(FILES_TO_CACHE);
})
.then(() => {
caches.keys().then(keyList => {
return Promise.all(
keyList.map(key => {
if (cacheWhitelist.indexOf(key) === -1) {
console.log("[ServiceWorker] removing old key in cache: ", key);
return caches.delete(key);
}
})
);
});
})
);
});
self.addEventListener("fetch", event => {
event.respondWith(
caches.match(event.request).then(response => {
if (response) return response;
return fetch(event.request)
.then(response => {
if (!response || response.status !== 200 || response.type !== "basic")
return response;
// IMPORTANT: Clone the response. A response is a stream
// and because we want the browser to consume the response
// as well as the cache consuming the response, we need
// to clone it so we have two streams.
let responseToCache = response.clone();
caches
.open(CACHE_NAME)
.then(cache => cache.put(event.request, responseToCache));
return response;
})
.catch(err => {
// fallback mechanism
console.error(
"[ServiceWorker: ERROR] ",
err.message,
event.request.url
);
return caches.open(CACHE_NAME).then(cache => {
return cache.match("./index.html");
});
});
})
);
});