workbox icon indicating copy to clipboard operation
workbox copied to clipboard

"Generate offline fallback SW" mode in build tools

Open jeffposnick opened this issue 4 years ago • 1 comments

Many developers would like to use a service worker for an offline fallback page, e.g. to meet the minimal offline support criteria, without integrating Workbox's build tools into their site deployment, which is otherwise necessary in order to use precaching-based solutions.

We can automate this process in Workbox's build tools via a new generateOfflineFallback mode, along the lines of:

npx workbox-cli generateOfflineFallback path/to/local/offline.html

(or run via the equivalent workbox-build or workbox-webpack-plugin interface).

The input could be a local HTML file, and the output could be a service worker that combined workbox-strategies, workbox-routing, and workbox-navigation-preload to cache and serve the HTML file as well as any subresources it depends on (using jsdom or a similar library to determine this as a best-effort).

Instead of using a precache manifest, which would require re-running this generateOfflineFallback command each time a given site is rebuilt, it would use best-effort versioning by including a time stamp as part of the generated service worker. It would be the responsibility of each site owner to re-run the command if they want to ensure that changes to their offline HTML or subresources get picked up by existing clients.

This new mode would be aimed at developers who do not want to integrate Workbox's build tools into their site's build process, which is required when using precaching. It would offer a one-off service worker generation mode

Alternatives

Developers who want to use precaching and are using the existing generateSW mode can already do all this with a configuration along the lines of:

generateSW({
  // ... other generateSW config options...
  navigationPreload: true,
  runtimeCaching: [{
    urlPattern: ({request}) => request.mode === 'navigate',
    handler: 'NetworkOnly',
    options: {
      precacheFallback: {
        // This URL needs to be included in your precache manifest.
        fallbackURL: '/offline.html',
      },
    },
  }],
});

CC: @andreban

jeffposnick avatar Apr 14 '21 14:04 jeffposnick

Especially like the idea that this would take care of sub resources. 👍

tomayac avatar Apr 14 '21 14:04 tomayac

I tried with the example you provided but I cannot manage to make it work. It seems that index.html gets loaded regardless of this. The only requests tha I can see passing through the urlPattern func are the one made by the html to load external fonts etc

fteotini avatar Jan 24 '23 15:01 fteotini