sw.js
2.11 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
76
77
importScripts('workbox-sw.prod.v2.1.2.js');
// self.addEventListener('install', function(event) {
// event.waitUntil(
// caches.open('common-cache').then(function(cache) {
// return cache.addAll([
// 'https://devcdn.yoho.cn:7001/index.css'
// ]);
// })
// );
// });
self.addEventListener('error', event => {
// 上报错误信息
// 常用的属性:
// event.message
// event.filename
// event.lineno
// event.colno
// event.error.stack
})
self.addEventListener('unhandledrejection', event => {
// 上报错误信息
// 常用的属性:
// event.reason
})
self.addEventListener('fetch', function (event) {
console.log(event.request);
event.respondWith(
caches.match(event.request).then(function (response) {
// 来来来,代理可以搞一些代理的事情
// 如果 Service Worker 有自己的返回,就直接返回,减少一次 http 请求
if (response) {
return response;
}
// 如果 service worker 没有返回,那就得直接请求真实远程服务
let request = event.request.clone(); // 把原始请求拷过来
return fetch(request).then(function (httpRes) {
// http请求的返回已被抓到,可以处置了。
// 请求失败了,直接返回失败的结果就好了。。
if (!httpRes || httpRes.status !== 200) {
return httpRes;
}
// 请求成功的话,将请求缓存起来。
let responseClone = httpRes.clone();
console.log(httpRes)
caches.open('custom-cache').then(function (cache) {
cache.put(event.request, responseClone);
});
return httpRes;
}).catch(console.error);
})
);
});
const workboxSW = new self.WorkboxSW({
clientsClaim: true,
skipWaiting: true
});
workboxSW.precache([
{
"url": "/sw.js"
},
{
"url": "/workbox-sw.prod.v2.1.2.js"
}
]);