-
Notifications
You must be signed in to change notification settings - Fork 0
/
service-worker.js
72 lines (62 loc) · 1.8 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
var CACHE_NAME = 'v1';
function cacheInitialResources() {
return caches.open(CACHE_NAME).then(cache =>
cache.addAll([
'/',
'/blog/',
'/offline',
])
);
}
function clearOldCaches() {
return caches.keys()
.then(cacheNames =>
Promise.all(
cacheNames.map(cacheName => {
if (cacheName !== CACHE_NAME) {
return caches.delete(cacheName);
}
})
)
)
.then(() => clients.claim())
}
function fetchOrGoToOfflinePage(fetchEvent) {
var eventRequest = fetchEvent.request;
// going somewhere?
if (eventRequest.mode === 'navigate') {
return fetch(eventRequest)
.catch(() =>
caches.match(eventRequest.url).then(cachedPage =>
cachedPage || caches.match('/offline').then(cachedOfflinePage =>
// workaround for https://issues.chromium.org/issues/41288530
cachedOfflinePage && new Response(cachedOfflinePage.body)
)
)
);
}
// "hack" until GitHub pages supports a longer Cache-Control https://github.com/orgs/community/discussions/11884
if (eventRequest.url.endsWith('.css')) {
return Promise.all([
fetch(eventRequest),
caches.open(CACHE_NAME)
]).then(
([response, cache]) => cache.add(eventRequest.url, response).then(() => response),
(error) => caches.match(eventRequest.url)
);
}
return fetch(eventRequest);
}
function onInstall(installEvent) {
skipWaiting();
installEvent.waitUntil(cacheInitialResources());
}
function onActivate(activateEvent) {
activateEvent.waitUntil(clearOldCaches);
}
function onFetch(fetchEvent) {
fetchEvent.respondWith(fetchOrGoToOfflinePage(fetchEvent));
}
addEventListener('install', onInstall);
addEventListener('activate', onActivate);
addEventListener('fetch', onFetch);