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

Workbox v5迁移后离线访问新页面异常:no-response错误排查

Fixing Offline Page & No-Response Errors in Workbox v5

Hey there, let's sort out that offline page issue you're facing! The "no-response" error and failed offline navigation to new pages come from a couple of clear issues in your current service worker code—let's break them down and fix them step by step.

Key Issues in Your Current Code

  1. Duplicate HTML Route Registration: You have two separate registerRoute calls targeting .html files. The first one (using NetworkFirst) takes priority, so the second route meant to handle 404/offline cases never runs.
  2. Undefined articleHandler: You're trying to call articleHandler.handle(args) but this variable isn't declared anywhere—this causes silent failures that lead directly to the no-response error.
  3. Missing Offline Fallback for Network Failures: The NetworkFirst strategy throws a no-response error when offline and the requested HTML isn't cached. You need to explicitly catch this scenario and serve your offline.html.

Corrected Service Worker Code

Here's the fixed version with comments explaining each change:

importScripts('https://storage.googleapis.com/workbox-cdn/releases/5.1.4/workbox-sw.js')

if (workbox) {
  console.log('Yay! Workbox is loaded');

  // Precache critical offline/404 pages
  workbox.precaching.precacheAndRoute(
    [
      { url: "404.html", revision: "ca66a569ea978f2cca26acf6994d7e49" },
      { url: "offline.html", revision: "112452c5d7bf793db0ab9a37cf30d178" }
    ]
  );

  // Cache non-HTML assets (images, CSS, JS) with CacheFirst, 30-day expiration
  workbox.routing.registerRoute(
    /\.(?:png|gif|jpg|svg|css|js|json)$/,
    new workbox.strategies.CacheFirst({
      cacheName: 'nonhtml-cache',
      plugins: [
        new workbox.expiration.ExpirationPlugin({
          maxEntries: 50,
          maxAgeSeconds: 30 * 24 * 60 * 60, // 30 Days
        })
      ]
    })
  );

  // Handle HTML requests with NetworkFirst, plus offline/404 fallbacks
  workbox.routing.registerRoute(
    /\.html$/,
    new workbox.strategies.NetworkFirst({
      cacheName: 'html-cache',
      plugins: [
        new workbox.cacheableResponse.CacheableResponsePlugin({
          statuses: [0, 200, 206],
        }),
        new workbox.expiration.ExpirationPlugin({
          maxEntries: 50,
          maxAgeSeconds: 5 * 60, // 5 Minutes
        })
      ]
    }),
    'GET'
  );

  // Global catch handler for all failed requests (including offline no-response cases)
  workbox.routing.setCatchHandler(async ({ event }) => {
    switch (event.request.destination) {
      case 'document':
        // For HTML requests: serve 404 if cached response is 404, else offline.html
        try {
          const cachedResponse = await caches.match(event.request);
          if (cachedResponse && cachedResponse.status === 404) {
            return caches.match('404.html');
          }
          return caches.match('offline.html');
        } catch (err) {
          return caches.match('offline.html');
        }
      default:
        // For other assets, let the browser handle the failure
        return Response.error();
    }
  });
} else {
  console.log('Boo! Workbox did not load');
}

What Changed & Why

  1. Removed Duplicate HTML Route: We combined HTML handling into one registerRoute call to eliminate routing conflicts.
  2. Added Global Catch Handler: The setCatchHandler method catches all failed requests—including when offline and the HTML isn't cached, which was causing your "no-response" error. It serves the right fallback:
    • If the cached response is a 404, it serves 404.html
    • For all other offline/failed HTML requests, it serves offline.html
  3. Eliminated Undefined Variable: We removed the unused articleHandler reference that was causing hidden failures.

Testing the Fix

  1. Clear Old Cache & SW: In your browser's dev tools (Application tab), unregister the old service worker and clear all caches to start fresh.
  2. Reload & Register: Refresh your site to register the updated service worker.
  3. Test Offline: Toggle offline mode in dev tools and visit a new HTML page—you should see offline.html instead of the ERR_FAILED message.
  4. Test 404: Visit a non-existent HTML page (like /missing-page.html) while online, and you'll get your 404.html fallback.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.11 08:01:50