Workbox Strategies provides the most common caching strategies so itโs easy to apply them in your service worker Example : - using Twitter as an example
How to implement Cache Strategies
We're going to use Twitter as an example to best explain how best to implement these strategies so that you don't just cache anything.
1. Stale-While-Revalidate
This is a fairly common strategy where having the most up-to-date resource is not vital to the application. Respond the request as quickly as possible with a cached response if available, falling back to the network request if itโs not cached. The network request is then used to update the cache.
workbox.routing.registerRoute(
new RegExp('/images/profile-picture/'),
workbox.strategies.staleWhileRevalidate()
);
2. Cache First (Cache Falling Back to Network)
Best for for assets that are non-critical and can be gradually cached.
workbox.routing.registerRoute(
new RegExp('/media/'),
workbox.strategies.cacheFirst()
);
3. Network First (Network Falling Back to Cache)
Best for requests that are updating frequently. By default it will try and fetch the latest request from the network. If the request is successful, itโll put the response in the cache. If the network fails to return a response, the caches response will be used
workbox.routing.registerRoute(
new RegExp('/latest-tweets/'),
workbox.strategies.networkFirst()
);
4. Network Only
Best if you require specific requests to be fulfilled from the network
workbox.routing.registerRoute(
new RegExp('/settings/'),
workbox.strategies.networkOnly()
);