-
Notifications
You must be signed in to change notification settings - Fork 15
/
sw.js
106 lines (96 loc) · 2.54 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
93
94
95
96
97
98
99
100
101
102
103
104
105
106
importScripts('https://storage.googleapis.com/workbox-cdn/releases/6.5.4/workbox-sw.js')
const { precaching, routing, strategies } = workbox;
const {registerRoute} = workbox.routing;
const {CacheFirst, NetworkFirst} = workbox.strategies;
const {CacheableResponse, CacheableResponsePlugin} = workbox.cacheableResponse;
self.skipWaiting(); // 跳过等待,立即激活 SW
// self.clients.claim(); // 控制所有同源客户端,确保使用新缓存策略,不要用?
// 离线优先,安装后立即生效
self.addEventListener('install', (event) => {
const urls = [{
url: "data.js",
revision: null
}, {
url: "utils.js",
revision: null
}, {
url: "lang.js",
revision: null
}, {
url: "script.js",
revision: null
}, {
url: "tailwind.css",
revision: null
}, {
url: "main.css",
revision: null
}, {
url: "registerSW.js",
revision: null
}, {
url: "index.html",
revision: null
}, {
url: "manifest.webmanifest",
revision: null
}];
const precacheManifest = urls.map((url) => {
return {
url: url.url,
revision: url.revision || null
};
});
precaching.precacheAndRoute(precacheManifest);
});
// 清理缓存
self.addEventListener('activate', (event) => {
event.waitUntil(caches.keys().then((cacheNames) => {
return Promise.all(
cacheNames.filter((cacheName) => {
return cacheName.startsWith('workbox-');
}).map((cacheName) => {
return caches.delete(cacheName);
})
);
}));
});
// registerRoute(({request}) => request.destination === 'style', new CacheFirst());
registerRoute(({request}) => {
console.log('request.destination', request.destination)
return /script|document/.test(request.destination)
}, new NetworkFirst({
networkTimeoutSeconds: 3,
cacheName: 'static-resources-critical',
plugins: [
new CacheableResponsePlugin({
statuses: [200],
}),
],
}));
registerRoute(({request}) => {
console.log('request.destination', request.destination)
return /image|style/.test(request.destination)
}, new CacheFirst({
networkTimeoutSeconds: 3,
cacheName: 'static-resources',
plugins: [
new CacheableResponsePlugin({
statuses: [200],
}),
],
}));
// // 处理 navigation 请求
// routing.registerRoute(
// new strategies.NetworkFirst({
// cacheName: 'navigation-cache',
// plugins: [
// new CacheableResponsePlugin({
// statuses: [0, 200],
// })
// ]
// }),
// // new workbox.NavigationRoute(({ event }) => {
// // return '/';
// // })
// );