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

如何在PWA的Service Worker中正确编写Fetch事件监听器?

PWA缓存优先Fetch监听器问题排查与修复

你的代码逻辑确实是缓存优先策略的基础实现——先尝试从缓存匹配请求资源,命中则返回缓存内容,未命中则发起网络请求。但可能因为以下几个原因导致功能未正常生效,对应的修复方案如下:

  • 缓存未提前填充
    你需要确保目标资源已经被预缓存到缓存存储空间中。可以在install事件中完成预缓存操作,示例代码:

    self.addEventListener('install', (e) => {
      e.waitUntil(
        caches.open('my-cache-v1')
          .then((cache) => cache.addAll([
            // 列出需要预缓存的文件路径,根据你的实际项目调整
            '/',
            '/index.html',
            '/styles.css',
            '/app.js'
          ]))
      );
    });
    

    如果没有这一步预缓存,caches.match自然找不到对应的资源,会直接走网络请求。

  • 缓存匹配精度问题
    caches.match(e.request)默认会遍历所有缓存存储空间查找匹配资源,如果你维护了多个缓存,建议指定具体缓存名称来提高匹配准确性:

    e.respondWith(
      caches.open('my-cache-v1').then((cache) => {
        return cache.match(e.request).then((response) => {
          return response || fetch(e.request);
        });
      })
    );
    
  • 缺失网络失败兜底处理
    当前代码如果遇到离线且缓存未命中的情况,会返回错误响应。可以添加兜底逻辑,返回自定义的离线页面:

    e.respondWith(
      caches.match(e.request).then((response) => {
        return response || fetch(e.request).catch(() => {
          // 返回预缓存的离线页面
          return caches.match('/offline.html');
        });
      })
    );
    
  • 服务工作者状态异常
    检查浏览器开发者工具的Application -> Service Workers面板,确认服务工作者已成功注册并激活,没有被旧版本覆盖。

调整后的完整示例

self.addEventListener('install', (e) => {
  e.waitUntil(
    caches.open('my-cache-v1')
      .then((cache) => cache.addAll([
        '/',
        '/index.html',
        '/offline.html'
        // 根据项目需求添加其他需要预缓存的资源
      ]))
  );
});

self.addEventListener('fetch', (e) => {
  console.log(e.request.url);
  e.respondWith(
    caches.match(e.request).then((response) => {
      // 缓存优先,网络失败返回离线页面
      return response || fetch(e.request).catch(() => caches.match('/offline.html'));
    })
  );
});

内容的提问来源于stack exchange,提问作者user94625

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 03:01:06