Repository navigation
Expand file tree
/
Copy pathsw.js
More file actions
54 lines (50 loc) · 2.16 KB
/
Copy pathsw.js
File metadata and controls
54 lines (50 loc) · 2.16 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
/* 练习记录 · 离线缓存
目的:健身房地下层没信号时,也能从主屏幕秒开。
策略:先用缓存立刻显示,同时后台拉一次最新版;下次打开即为新版。
发布新版后如果手机迟迟不更新,把下面 CACHE 的版本号加 1,手机会强制换成新文件。 */
const CACHE = 'gymlog-v2';
const ASSETS = ['./', './index.html'];
self.addEventListener('install', e => {
// cache: 'reload' 跳过浏览器自己的 HTTP 缓存,确保装进来的是服务器上的最新文件
e.waitUntil(caches.open(CACHE)
.then(c => c.addAll(ASSETS.map(u => new Request(u, { cache: 'reload' }))))
.then(() => self.skipWaiting()));
});
self.addEventListener('activate', e => {
e.waitUntil(
caches.keys()
.then(ks => Promise.all(ks.filter(k => k !== CACHE).map(k => caches.delete(k))))
.then(() => self.clients.claim())
);
});
// 读缓存:先精确匹配,再忽略查询串,最后退回 index.html
async function fromCache(req) {
const c = await caches.open(CACHE);
return (await c.match(req)) ||
(await c.match(req, { ignoreSearch: true })) ||
(await c.match('./index.html')) ||
(await c.match('./'));
}
self.addEventListener('fetch', e => {
const req = e.request;
if (req.method !== 'GET') return;
if (new URL(req.url).origin !== self.location.origin) return;
e.respondWith((async () => {
const hit = await fromCache(req);
if (hit) return hit;
try { return await fetch(req); }
catch (err) {
return new Response('离线,且本地没有缓存。请联网后再打开一次。', {
status: 503, headers: { 'Content-Type': 'text/plain; charset=utf-8' }
});
}
})());
// 后台更新缓存,不阻塞显示。
// 用网址重新发请求:页面导航请求(mode=navigate)带上额外参数时,部分浏览器会直接报错,导致缓存永远不更新
e.waitUntil((async () => {
try {
const res = await fetch(req.url, { cache: 'no-cache', credentials: 'same-origin' });
if (res && res.ok) { const c = await caches.open(CACHE); await c.put(req, res.clone()); }
} catch (err) { /* 断网时保持旧缓存 */ }
})());
});