This repository has been archived by the owner on Jan 20, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
service-worker.js
82 lines (52 loc) · 1.89 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
82
self.addEventListener('fetch', (event) => {
const method = howToHandle(event.request);
if (method) {
event.respondWith(method(event));
}
});
const howToHandle = (request) => {
if (request.mode === 'navigate') {
return networkThenCache;
} else if (request.method === 'GET' && request.url.startsWith(location.origin)) {
if (request.url.endsWith('.jpg')) {
return staleWhileRevalidate;
}
return networkThenCache;
}
};
/**
* Returns a fresh version of a resource. If the fetch fails, it'll return a
* cached value if possible. It will also update the cache once the fetch is
* completed.
*/
const networkThenCache = async (event) => {
const request = event.request;
const normalizedUrl = new URL(request.url);
normalizedUrl.search = '';
normalizedUrl.hash = '';
const resourcePromise = fetch(normalizedUrl, {
redirect: request.redirect
});
event.waitUntil(updateCacheAfter(resourcePromise, normalizedUrl));
return resourcePromise
.then(response => response.clone())
.catch(() => caches.match(normalizedUrl));
};
/**
* Returns a stale version of a resource while simultaneously fetching a newer
* version. Provides a fast response while updating for future visits.
*/
const staleWhileRevalidate = async (event) => {
const normalizedUrl = new URL(event.request.url);
normalizedUrl.search = '';
normalizedUrl.hash = '';
const resourcePromise = fetch(normalizedUrl);
event.waitUntil(updateCacheAfter(resourcePromise, normalizedUrl));
const cachedResource = await caches.match(normalizedUrl);
return cachedResource || resourcePromise;
};
const updateCacheAfter = async (promise, key) => {
const cache = await caches.open('static-content');
const value = await promise.then(response => response.clone());
return cache.put(key, value);
};