-
Notifications
You must be signed in to change notification settings - Fork 0
/
sw.js
92 lines (78 loc) · 2.04 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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
importScripts('https://cdn.jsdelivr.net/npm/workbox-cdn@5.1.3/workbox/workbox-sw.js');
workbox.setConfig({
modulePathPrefix: 'https://cdn.jsdelivr.net/npm/workbox-cdn@5.1.3/workbox/'
});
//关闭日志
self.__WB_DISABLE_DEV_LOGS = true;
const { core, precaching, routing, strategies, expiration } = workbox;
const { CacheFirst, NetworkFirst, NetworkOnly, StaleWhileRevalidate } = strategies;
const { ExpirationPlugin } = expiration;
const cacheSuffixVersion = '_20200610';
core.setCacheNameDetails({
prefix: 'bycg',
suffix: cacheSuffixVersion
});
self.addEventListener('activate', (event) => {
event.waitUntil(
caches.keys().then((keys) => {
return Promise.all(keys.map((key) => {
if (!key.includes(cacheSuffixVersion)) return caches.delete(key);
}));
})
);
});
core.skipWaiting();
core.clientsClaim();
/**
* 缓存第三方引用
*/
routing.registerRoute(
/.*(cdn.jsdelivr.net|at.alicdn.com)/,
new CacheFirst({
cacheName: 'static-cdn' + cacheSuffixVersion,
fetchOptions: {
mode: 'cors',
credentials: 'omit'
},
plugins: [
new ExpirationPlugin({
maxAgeSeconds: 30 * 24 * 60 * 60,
purgeOnQuotaError: true
})
]
})
);
//不作缓存
routing.registerRoute(
/\/sw.js/,
new NetworkOnly()
);
//缓存图片
routing.registerRoute(
/.*\.(?:png|jpg|jpeg|svg|gif|webp)/,
new CacheFirst({
cacheName: 'static-image' + cacheSuffixVersion,
})
);
//缓存js css
routing.registerRoute(
/.*\.(css|js)$/,
new CacheFirst({
cacheName: 'static-js-css' + cacheSuffixVersion,
})
);
//本站其他文件
routing.registerRoute(
({ url }) => {
return url.hostname === location.hostname
},
new NetworkFirst({
cacheName: 'static-other' + cacheSuffixVersion,
plugins: [
new ExpirationPlugin({
maxEntries: 50,
purgeOnQuotaError: true
})
]
})
);