sw.js
1.85 KB
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
/* eslint-env worker */
import 'whatwg-fetch';
import WorkboxSW from 'workbox-sw';
import parseQs from 'yoho-qs/parse';
const config = {
customCacheUrl: [
/^https:\/\/(.*)cdn\.yoho\.cn/i,
/^https:\/\/(.*)static\.yhbimg\.com/i
],
precachePage: [
'/offline.html'
],
precacheStaticFile: [
'/index.css',
'/common.css',
'/libs.js',
'/common.offline.js',
'/font/iconfont.woff',
'/img/common/404.png'
]
};
const qs = parseQs(self.location.search.substr(1));
const workboxSW = new WorkboxSW({
clientsClaim: true,
skipWaiting: true
});
const cacheFirstStrategy = workboxSW.strategies.cacheFirst({
cacheableResponse: {
statuses: [0, 200]
},
cacheExpiration: {
maxEntries: 1000,
maxAgeSeconds: 7 * 24 * 60 * 60 // 7 day
}
});
// 特殊路径的预缓存文件文件
const precacheFile = [{
url: '/sw.js?t=' + qs.t + '&staticServer=' + qs.staticServer
}].concat(config.precacheStaticFile.map(file => {
// 根据业务自定义资源路径
const url = self.location.protocol + qs.staticServer + file + '?t=' + qs.t;
return {
url: url
};
})).concat(config.precachePage.map(page => {
return {
url: page
};
}));
// 预加载文件
workboxSW.precache(precacheFile);
// 自定义缓存
config.customCacheUrl.forEach(urlRegExp => {
workboxSW.router.registerRoute(
urlRegExp,
cacheFirstStrategy
);
});
// 所有网络走 worker,异常时增加离线页面
workboxSW.router.registerRoute(/.*/, args => {
return workboxSW.strategies.networkFirst().handle(args).then(res => {
if (res || args.event.request.mode !== 'navigate') {
return res;
}
// navigate 请求失败后,返回网络异常页面
return caches.match('offline.html');
});
});