s-leg3ndz
s-leg3ndz

Reputation: 3528

Workbox StaleWhileRevalidate and offline fallback

Is it possible to return an offline fallback for StaleWhileRevalidate strategie with Workbox ?

const urlHandler = new StaleWhileRevalidate({
  cacheName: 'routes',
  plugins,
});

registerRoute(
  ({ request }) => request.mode === 'navigate',
  ({ event }) =>
    urlHandler.handle({ event }).catch(() => caches.match(FALLBACK_HTML_URL)),
);

This code work only if the request is on cache .. but for new URL not cached (but with network), it show directly the Offline fallback :/

Anyone have already test this usecase ?

Upvotes: 0

Views: 437

Answers (1)

Jeff Posnick
Jeff Posnick

Reputation: 56104

In Workbox v6+, the cleanest way to do this would be to use a handlerDidError plugin:

import {registerRoute} from 'workbox-routing';
import {StaleWhileRevalidate} from 'workbox-strategies';


registerRoute(
  ({request}) => request.mode === 'navigate',
  new StaleWhileRevalidate({
    cacheName: 'routes',
    plugins: [
      {handlerDidError: () => caches.match(FALLBACK_HTML_URL)},
      // Add any other plugins here.
    ],
  })
);

Upvotes: 1

Related Questions