完善预览页面
This commit is contained in:
+36
-9
@@ -53,17 +53,44 @@ self.addEventListener('fetch', (event) => {
|
||||
// 跳过 API/SSE/预览/交付取件,避免缓存动态数据(预览页需实时;/f/ 同链内容会随重新 save 变化)
|
||||
if (url.pathname.startsWith('/api/') || url.pathname.startsWith('/sse') || url.pathname.startsWith('/preview') || url.pathname.startsWith('/f/')) return;
|
||||
|
||||
// vendor 预览页发出的根绝对请求(fetch('/') 自刷新、EventSource('/events') 等,Referer 是预览页):
|
||||
// 内容随文档变化,既不缓存,也不能把 office 文档页写进 '/' 这类 SPA 缓存键。
|
||||
if (request.referrer) {
|
||||
try {
|
||||
const rp = new URL(request.referrer).pathname;
|
||||
if (rp === '/preview' || rp.startsWith('/preview/')) return;
|
||||
} catch (_) {}
|
||||
}
|
||||
|
||||
// HTML/登录页:网络优先
|
||||
if (request.mode === 'navigate' || request.destination === 'document') {
|
||||
event.respondWith(
|
||||
fetch(request)
|
||||
.then((resp) => {
|
||||
const copy = resp.clone();
|
||||
caches.open(RUNTIME_CACHE).then((cache) => cache.put(request, copy));
|
||||
return resp;
|
||||
})
|
||||
.catch(() => caches.match(request).then((r) => r || caches.match('/')))
|
||||
);
|
||||
// 静态站文件是绑定挂载、外部工具改动非原子:刷新时机撞上写入瞬间会拿到半截 HTML
|
||||
// (脚本/样式缺一半 → 无样式裸首页假象)。读成文本校验收尾标签,残破则稍候重试一次;
|
||||
// 两次都残破也照常返回,只有 ok 的快照才进缓存(残破页进缓存会被离线兜底永久化)。
|
||||
event.respondWith((async () => {
|
||||
let last = null;
|
||||
for (let i = 0; i < 2; i++) {
|
||||
try {
|
||||
const resp = await fetch(request);
|
||||
if (!resp.ok || resp.type !== 'basic') return resp;
|
||||
last = { txt: await resp.text(), resp };
|
||||
} catch (e) {
|
||||
if (last) break; // 已有残破快照:降级返回它
|
||||
if (i === 1) throw e;
|
||||
await new Promise((r) => setTimeout(r, 250));
|
||||
continue;
|
||||
}
|
||||
if (/<\/html>\s*$/i.test(last.txt)) break;
|
||||
if (i === 0) await new Promise((r) => setTimeout(r, 250));
|
||||
}
|
||||
const h = new Headers(last.resp.headers);
|
||||
// 重建响应体后 Content-Length 已失真,连同二进制透传头一并剔除(也是 Response 构造禁设项)
|
||||
['content-length', 'content-encoding', 'content-transfer-encoding'].forEach((k) => h.delete(k));
|
||||
const out = new Response(last.txt, { status: last.resp.status, statusText: last.resp.statusText, headers: h });
|
||||
const complete = /<\/html>\s*$/i.test(last.txt);
|
||||
if (complete) caches.open(RUNTIME_CACHE).then((cache) => cache.put(request, out.clone()));
|
||||
return out;
|
||||
})().catch(() => caches.match(request).then((r) => r || caches.match('/'))));
|
||||
return;
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user