-
Notifications
You must be signed in to change notification settings - Fork 0
/
serviceworker.js
50 lines (45 loc) · 1.41 KB
/
serviceworker.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
// Mozilla Service Worker Cookbook 'network or cache' recipe: https://serviceworke.rs/strategy-network-or-cache.html
const CACHE = 'network-or-cache';
self.addEventListener('install', evt => {
console.log('The service worker is being installed.');
evt.waitUntil(precache());
});
self.addEventListener('fetch', evt => {
console.log('The service worker is serving the asset.');
evt.respondWith(
fromNetwork(evt.request, 400).catch(() => {
return fromCache(evt.request);
})
);
});
function precache() {
return caches.open(CACHE).then(cache => {
return cache.addAll([
'./index.html',
'./view-container.html',
'./view-form.html',
'./favicon.ico',
'js/frame-api.js',
'js/index.js',
'js/view-container.js',
'js/view-form.js',
'./node_modules/lit-html/lit-html.js'
]);
});
}
function fromNetwork(request, timeout) {
return new Promise((fulfill, reject) => {
const timeoutId = setTimeout(reject, timeout);
fetch(request).then(response => {
clearTimeout(timeoutId);
fulfill(response);
}, reject);
});
}
function fromCache(request) {
return caches.open(CACHE).then(cache => {
return cache.match(request).then(matching => {
return matching || Promise.reject('no-match');
});
});
}