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

Service Worker请求未缓存JS文件时返回离线HTML页面问题求助

问题原因

你当前的Service Worker代码未对请求类型做区分,所有请求触发网络异常时都会统一返回offline.html,因此未缓存的JS文件请求失败后拿到的是HTML内容,触发JS语法错误。

修复方案

在fetch事件回调的最外层增加导航请求判断,仅对HTML页面的导航请求做离线页兜底,其他类型的资源请求失败时直接抛出网络错误即可。

const cacheName = 'offline-v1900'; //increment version to update cache
// cache these files needed for offline use
const appShellFiles = [
    './offline.html',
    './css/bootstrap.min.css',
    './img/logo/logo.png',
    './js/jquery-3.5.1.min.js',
    './js/bootstrap.min.js',
];

self.addEventListener("fetch", (e) => {
  // 仅对导航请求(HTML页面请求)做离线兜底逻辑
  if (e.request.mode !== 'navigate') {
    // 非导航请求走默认缓存+网络逻辑,失败返回原生网络错误
    e.respondWith(
      (async () => {
        const preloadResponse = await e.preloadResponse;
        if (preloadResponse) return preloadResponse;
        const cachedResponse = await caches.match(e.request);
        if (cachedResponse) return cachedResponse;
        return fetch(e.request);
      })()
    );
    return;
  }

  // 导航请求保留原有离线兜底逻辑
  e.respondWith(
    (async () => {
      try {
        const preloadResponse = await e.preloadResponse;
        if (preloadResponse) return preloadResponse;

        const cachedResponse = await caches.match(e.request);
        if (cachedResponse) return cachedResponse;

        const networkResponse = await fetch(e.request);
        return networkResponse;
      } catch (error) {
        const cachedResponse = await caches.match('offline.html');
        return cachedResponse;
      }
    })()
  );
});

如果后续需要对其他类型的资源做自定义兜底(比如图片请求失败返回占位图),可以单独对e.request.destination做判断处理,比如e.request.destination === 'script'对应JS请求、e.request.destination === 'image'对应图片请求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 14:24:00