-
Notifications
You must be signed in to change notification settings - Fork 8
/
serviceworker.js
62 lines (57 loc) · 1.57 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
51
52
53
54
55
56
57
58
59
60
61
62
const cacheVersion = '20251113';
const cacheList = [
'./',
'./index.html',
'./manifest.json',
'./manifest-ios.json',
'./manifest-mac.json',
'./icon/favicon.ico',
'./icon/icon-144.png',
'./icon/icon-256.png',
'./icon/icon-512.png',
'./icon/mac/icon-512.png',
'./css/base.css',
'./js/config.js',
'./js/plugins.js',
'./js/init.js'
];
// for (let i = 0; i < cacheList.length; i++) {
// const tail = cacheList[i].slice(cacheList[i].lastIndexOf('.'));
// if (['.css', '.js'].indexOf(tail) >= 0) {
// cacheList[i] += '?version=' + cacheVersion;
// };
// };
self.addEventListener('install', function(e) {
e.waitUntil(
caches.open(cacheVersion).then(function(cache) {
return cache.addAll(cacheList);
})
);
});
// 监听 fetch 事件,安装完成后,进行文件缓存
self.addEventListener('fetch', function(e) {
// console.log('fetch', e);
e.respondWith(
caches.match(e.request).then(function(cache) {
// 如果有 cache 则直接返回,否则通过 fetch 请求
return cache || fetch(e.request);
}).catch(function(err) {
console.log(err);
return fetch(e.request);
})
);
});
// 监听 activate 事件,清除缓存
self.addEventListener('activate', function(e) {
// console.log('activate', e);
e.waitUntil(
caches.keys().then(function(keys) {
return Promise.all(keys.map(function(key) {
if (key !== cacheVersion) {
return caches.delete(key);
};
}));
})
);
return self.clients.claim();
});