forked from cotes2020/jekyll-theme-chirpy
-
Notifications
You must be signed in to change notification settings - Fork 0
/
sw.js
75 lines (64 loc) · 1.61 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
63
64
65
66
67
68
69
70
71
72
73
74
75
---
layout: compress
# PWA service worker
---
self.importScripts('{{ "/assets/js/data/swcache.js" | relative_url }}');
const cacheName = 'chirpy-{{ "now" | date: "%Y%m%d.%H%M" }}';
function verifyDomain(url) {
for (const domain of allowedDomains) {
const regex = RegExp(`^http(s)?:\/\/${domain}\/`);
if (regex.test(url)) {
return true;
}
}
return false;
}
function isExcluded(url) {
for (const item of denyUrls) {
if (url === item) {
return true;
}
}
return false;
}
self.addEventListener('install', e => {
self.skipWaiting();
e.waitUntil(
caches.open(cacheName).then(cache => {
return cache.addAll(resource);
})
);
});
self.addEventListener('fetch', e => {
e.respondWith(
caches.match(e.request).then(r => {
/* console.log(`[sw] method: ${e.request.method}, fetching: ${e.request.url}`); */
return r || fetch(e.request).then(response => {
const url = e.request.url;
if (e.request.method !== 'GET'
|| !verifyDomain(url)
|| isExcluded(url)) {
return response;
}
return caches.open(cacheName).then(cache => {
/* console.log('[sw] Caching new resource: ' + e.request.url); */
cache.put(e.request, response.clone());
return response;
});
});
})
);
});
self.addEventListener('activate', e => {
e.waitUntil(
caches.keys().then(keyList => {
return Promise.all(
keyList.map(key => {
if(key !== cacheName) {
return caches.delete(key);
}
})
);
})
);
});