-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsw.js
62 lines (55 loc) · 1.71 KB
/
sw.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
var VERSION = '6';
this.addEventListener('install', function(e) {
e.waitUntil(caches.open(VERSION).then(cache => {
return cache.addAll([
'/',
'/sw.js',
'/index.html',
'/404.html',
'/css/hyde.css',
'/css/poole.css',
'/articles/review-ghas-code-scanning-enterprise.html',
'/articles/building-a-simple-website.html',
'/articles/centralised-vs-decentralised-devops.html',
'/articles/innersourcing.html',
'/articles/step-functions.html',
'articles/developer-evolution.html',
'/articles/page/2.html'
]);
}))
});
this.addEventListener('fetch', function(e) {
var tryInCachesFirst = caches.open(VERSION).then(cache => {
return cache.match(e.request).then(response => {
if (!response) {
return handleNoCacheMatch(e);
}
fetchFromNetworkAndCache(e);
return response
});
});
e.respondWith(tryInCachesFirst);
});
this.addEventListener('activate', function(e) {
e.waitUntil(caches.keys().then(keys => {
return Promise.all(keys.map(key => {
if (key !== VERSION)
return caches.delete(key);
}));
}));
});
function fetchFromNetworkAndCache(e) {
if (e.request.cache === 'only-if-cached' && e.request.mode !== 'same-origin') return;
return fetch(e.request).then(res => {
if (!res.url) return res;
if (new URL(res.url).origin !== location.origin) return res;
return caches.open(VERSION).then(cache => {
// TODO: figure out if the content is new and therefore the page needs a reload.
cache.put(e.request, res.clone());
return res;
});
}).catch(err => console.error(e.request.url, err));
}
function handleNoCacheMatch(e) {
return fetchFromNetworkAndCache(e);
}