How to implement a 'Cache then network' strategy using Workbox

Viewed 905

I'm trying to implemement a 'cache then network' strategy using Workbox.

I've set Workbox to use the staleWhileRevalidate runtimeCaching handler, but I'm not sure how best to update the page once/if the cache us updated from the network.

The docs say:

In addition to updating the appropriate caches, it will also trigger any appropriate plugins defined in the underlying RequestWrapper.

Would that be any use? Are there any examples of this strategy being done with Workbox (which, by the way, is a wonderful tool, so thank you to its maintainers)?

1 Answers

There's an example of using the BroadcastCacheUpdate functionality in a "standalone" fashion at https://workbox-samples.glitch.me/examples/workbox-broadcast-cache-update/

To use it along with staleWhileValidate via WorkboxSW's routing, you could do something like:

workboxSW.router.registerRoute(
  new RegExp('/some/path/prefix'),
  workboxSW.strategies.staleWhileRevalidate({
    cacheName: 'my-cache',
    broadcastUpdate: {
      channelName: 'my-update-channel'
    },
  })
);

You can see a complete example in the docs.

Related