What's the use case for Workbox NetworkOnly strategy

1k views Asked by At

I'm trying to wrap my head around service workers and WorkBox.

Workbox provides a number of strategies to handle loading data in offline. Everything is crystal clear except the NetworkOnly strategy. The question is simple.

Why do may need to use this NetworkOnly strategy in the first place?

If all it does is accessing the network and fail if we're offline, then I get the same effect with no router and no strategy at all. If I don't register a router for some URL and try to access it from an app I'll get exactly the same results, it will just fail.

Can somebody propose a more or less realistic use case when I might want to use this strategy?

1

There are 1 answers

0
Jeff Posnick On BEST ANSWER

It's probably the least-used strategy, but there are a few scenarios where it comes in handy.

When using setDefaultHandler() to specify a strategy (say, StaleWhileRevalidate) to use when there are no matching routes, you might want to explicitly create a route that matches some criteria and applies a NetworkFirst strategy:

import {NetworkOnly, StaleWhileRevalidate} from 'workbox-routing';
import {registerRoute, setDefaultHandler} from 'workbox-routing';

// Ensure that requests that include /api/ go against the network.
registerRoute(
  ({url}) => url.pathname.includes('/api'),
  new NetworkOnly()
);

setDefaultHandler(new StaleWhileRevalidate());

Additionally, using NetworkOnly allows you to apply Workbox plugins to respond to various lifecycle events, like requestWillFetch, fetchDidFail, and fetchDidSucceed.