你已处于离线状态,显示的是缓存的页面内容

更新了 sw

时间:2026-06-01   标签: blog, web, 分享, sw,

我在之前为博客配置 sw,但必须是脱机情况下才可以用,但我的博客部署在 ghpages 上就有个问题

即使不是脱机情况下也有可能无法访问

于是就加了如果连接超时了也走 sw

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
/* ---- 网络优先(带 3 秒超时): 页面请求 ---- */
/* 先尝试网络,3 秒拿不到或失败则回退缓存 */
function networkFirst(request) {
var timeout = 3000;

return Promise.race([
fetch(request).then(function (resp) {
return caches.open(CACHE_NAME).then(function (cache) {
cache.put(request, resp.clone());
return resp;
});
}),
new Promise(function (_, reject) {
setTimeout(function () {
reject(new Error("timeout"));
}, timeout);
}),
]).catch(function () {
return caches.match(request);
});
}

这样即使我不想打开魔法网络也可以通过 sw 查看文章



社交的

bilibiliemailYouTube