-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathservice-worker.js
42 lines (36 loc) · 1.08 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
const CACHE = "codejanitor";
const offlineFallbackPage = "/offline.html";
self.addEventListener("install", event => {
event.waitUntil(
caches.open(CACHE).then(cache => cache.add(offlineFallbackPage))
);
});
self.addEventListener("fetch", event => {
if (event.request.method !== "GET") {
return;
}
event.respondWith(
fetch(event.request)
.then(response => {
event.waitUntil(updateCache(event.request, response.clone()));
return response;
})
.catch(error => fromCache(event.request))
);
});
async function fromCache(request) {
const cache = await caches.open(CACHE);
const matching = await cache.match(request);
if (!matching || matching.status === 404) {
if (request.destination !== "document" || request.mode !== "navigate") {
return Promise.reject("no-match");
} else {
return cache.match(offlineFallbackPage);
}
}
return matching;
}
async function updateCache(request, response) {
const cache = await caches.open(CACHE);
return cache.put(request, response);
}