-
Notifications
You must be signed in to change notification settings - Fork 0
/
service-worker-template.js
63 lines (56 loc) · 1.45 KB
/
service-worker-template.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
// © Kay Sievers <[email protected]>, 2021-2022
// SPDX-License-Identifier: Apache-2.0
const name = '__NAME__';
const version = __VERSION__;
const files = [
__FILES__
];
// Receive commands from the application.
self.addEventListener('message', (e) => {
if (!e.data || !e.data.type)
return;
switch (e.data.type) {
case 'skipWaiting':
self.skipWaiting();
break;
}
});
// Install a new version of the files, bypass the browser's cache.
self.addEventListener('install', (e) => {
e.waitUntil(
caches.open(name + '-' + version).then((cache) => {
for (const file of files) {
fetch(file, {
cache: 'no-cache'
})
.then((response) => {
if (!response.ok)
throw new Error('Status=' + response.status);
return cache.put(file, response);
})
}
})
);
});
// After an upgrade, delete all other versions of the cached files.
self.addEventListener('activate', (e) => {
e.waitUntil(
caches.keys().then((keys) => {
return Promise.all(
keys.map((key) => {
if (key.startsWith(name + '-') && (key !== name + '-' + version))
return caches.delete(key);
})
);
})
);
});
// Try to serve the cached page, fall back to the network.
self.addEventListener('fetch', (e) => {
e.respondWith(
caches.match(e.request)
.then((response) => {
return response || fetch(e.request);
})
);
});