-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsw.js
45 lines (43 loc) · 1.85 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
const CACHE_NAME = `Game-Tracker-Beta`; // 定义缓存名称为 "Game-Tracker-Beta" // Define cache name as "Game-Tracker-Beta `"
// 使用 install 事件预缓存所有初始资源
// Use the install event to pre-cache all initial resources
self.addEventListener('install', event => {
event.waitUntil((async () => {
const cache = await caches.open(CACHE_NAME); // 打开缓存 // Open the cache
cache.addAll([ // 将以下资源添加到缓存 // Add the following resources to the cache
'/',
'Stylesheet/Newsticker.js',
'Stylesheet/Stylesheet.css'
]);
})());
});
// 当有网络请求时触发
// Triggered when there is a network request
self.addEventListener('fetch', event => {
event.respondWith((async () => {
const cache = await caches.open(CACHE_NAME); // 打开缓存 // Open the cache
// 从缓存中获取资源
// Get the resource from the cache
const cachedResponse = await cache.match(event.request);
if (cachedResponse) {
return cachedResponse; // 如果缓存中有响应,返回缓存响应 // If there is a response in the cache, return the cached response
} else {
try {
// 如果缓存中没有资源,尝试从网络获取
// If the resource was not in the cache, try the network
const fetchResponse = await fetch(event.request);
// 确保只缓存GET或HEAD请求
// Ensure that only GET or HEAD requests are cached
if (event.request.method === 'GET' || event.request.method === 'HEAD') {
// 将资源保存到缓存并返回
// Save the resource in the cache and return it
cache.put(event.request, fetchResponse.clone());
}
return fetchResponse;
} catch (e) {
// 网络请求失败
// The network failed
}
}
})());
});