You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React PWA中Service Worker无法渲染自定义offline.html页面求助

问题诊断与修复方案

代码中的核心错误

  1. Activate事件缓存清理逻辑错误
    你在activate事件里写了!-cacheWhiteList.includes(cacheName),多余的-导致条件判断完全失效,无法正确清理旧缓存,残留的旧缓存会干扰新缓存的生效。

  2. Fetch事件缓存匹配逻辑缺失
    当前fetch事件中,调用caches.match(event.request)后直接忽略了缓存结果,无论缓存是否存在都强制发起网络请求。离线且缓存被清除后,网络请求失败时,虽然会尝试匹配offline.html,但旧缓存清理失败可能导致该文件未被正确缓存。

修正后的Service Worker代码

const CACHE_NAME = "version-1";
const urlsToCache = ["index.html", "offline.html"];

// 安装Service Worker
self.addEventListener("install", event => {
    event.waitUntil(
        caches.open(CACHE_NAME)
            .then(cache => {
                console.log("缓存已打开");
                return cache.addAll(urlsToCache);
            })
    );
});

// 处理请求:网络优先,失败则回退缓存或离线页
self.addEventListener("fetch", event => {
    event.respondWith(
        fetch(event.request)
            .catch(() => {
                // 网络失败时,先尝试匹配请求的缓存,无匹配则返回离线页
                return caches.match(event.request)
                    .then(cachedResponse => cachedResponse || caches.match("offline.html"));
            })
    );
});

// 激活Service Worker并清理旧缓存
self.addEventListener("activate", event => {
    const cacheWhiteList = [CACHE_NAME];

    event.waitUntil(
        caches.keys()
            .then(cacheNames => Promise.all(
                cacheNames.map(cacheName => {
                    if (!cacheWhiteList.includes(cacheName)) {
                        return caches.delete(cacheName);
                    }
                })
            ))
            .then(() => self.clients.claim()) // 立即接管所有打开的页面
    );
});

生效与验证步骤

  1. 强制更新Service Worker
    打开浏览器开发者工具Application标签:

    • 勾选Update on reload
    • 点击Unregister注销当前Service Worker
    • 刷新页面,等待新SW完成安装激活
  2. 确认缓存存储
    在Application -> Cache Storage中,检查version-1缓存下是否包含index.html和offline.html

  3. 测试离线状态
    勾选开发者工具中的Offline选项,刷新页面,验证是否显示自定义的offline.html

内容的提问来源于stack exchange,提问作者Niranjan A S

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.23 12:24:21