-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsw.js
79 lines (69 loc) · 2.07 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
"use strict"
const CACHE_NAME = 'service-cache-by-test';
const urlToCache =[
'/',
'/styles/main.css',
'/script/main.js'
]
// 安装事件
self.addEventListener('install',function(event){
event.waitUntil(
caches.open(CACHE_NAME).then(function(cache){
console.log('Opened cache')
return cache.addAll(urlToCache)
})
)
})
self.addEventListener('fetch', function(event) {
event.respondWith(
caches.match(event.request)
.then(function(response) {
// Cache hit - return response
if (response) {
return response;
}
return fetch(event.request);
}
)
);
});
//
self.addEventListener('activate', event => {
console.log('V1 now ready to handle fetches!');
// 这里是更新
});
// // 判断是否跨域了
// const isCORSRequest = function(url, host) {
// return url.search(host) === -1;
// };
// const isValidResponse = function(response) {
// return response && response.status >= 200 && response.status < 400 && response.type !== 'basic'
// };
// const HOST_NAME = location.host;
// console.log(location.host)
// const handleFetchRequest = function(req) {
// const newRequest = isCORSRequest(req.url, HOST_NAME) ? new Request(req.url, {mode: 'cors'}) :req;
// return caches.match(newRequest).then(function(response) {
// // Cache hit - return response
// if (response) {
// return response;
// }
// const fetchRequest = newRequest.clone();
// return fetch(fetchRequest)
// .then(function(response) {
// // Check if we received an valid response
// if (isValidResponse(response)) {
// const responseToCache = response.clone();
// caches.open(CACHE_NAME).then(function(cache) {
// cache.put(newRequest, responseToCache);
// });
// }
// return response;
// });
// });
// };
// const onFetch = function(event) {
// event.respondWith(handleFetchRequest(event.request));
// };
// // 更新事件
// self.addEventListener('fetch', onFetch);