javascriptreactjsservice-workerviteworkbox

My website using Vite PWA sending 100+ workbox initiated requests for small js scripts when the site is upgraded to a newer version


I just migrated a react route-based code-splitting site to Vite.js with its PWA plugin. After upgrading the production site to the latest version, I reloaded the page in Chrome and found that the workbox sending 100+ requests for js scripts in the background. I recognized the scripts as their names come from my react component files. This fetching only happens every time the site is upgraded and the service worker is updated and its cache is cleared:

enter image description here

enter image description here

I checked the responses of the js scripts and they were all redirected to the index.html files.

It seems that it only happens in Chrome. Firebox doesn't have any issues.

export default defineConfig(async () => {
  return {
    plugins: [
      importToCDN(),
      VitePWA({
        base: "/",
        registerType: "prompt",
        manifest: {
          name: "xxx",
          short_name: "xxx",
          icons: xxx,
          display: "standalone",
          start_url: `xxx`,
          orientation: "portrait",
        },
      }),
      react({
        babel: {
          parserOpts: {
            plugins: ["decorators-legacy", "classProperties"],
          },
        },
        include: "**/*.{jsx,tsx}",
      }),
      viteS3(),
    ],
  };
});

React Route Code Splitting Example:

import React, { lazy, Suspense } from ‘react’;
import ReactDOM from ‘react-dom’;

const router = createBrowserRouter([
  {
    path: "/",
    element: (
       <React.Suspense>
           <Outlet />
       </React.Suspense>
    ),
    children: [
     {
        path: "/home",
        lazy: () => import("./pages/home"),
     },
     {
        path: "/about",
        lazy: () => import("./pages/about"),
     }
    ],
  },
]);


const root = createRoot(document.getElementById("container")); // createRoot(container!) if you use TypeScript
root.render(
    <RouterProvider router={router} />

);


Is it normal for the workbox/service worker to send so many requests like this every time a newer version of the site is launched?


Solution

  • The behavior you're observing is normal with Workbox and Service Workers for sites with route-based code splitting. Each JavaScript chunk generated by Vite.js is treated as a separate resource by the Service Worker, and Workbox attempts to cache each of these chunks separately.

    The redirection to index.html might be due to your server or Vite.js configuration, which might be set up to serve index.html as a fallback for missing files.

    Browser differences could stem from how Chrome and Firefox handle Service Workers and caching.

    If this behavior is problematic for your use case, you could consider adjusting your Workbox and Service Worker configuration to alter caching strategies or exclude certain chunks from being pre-cached.