The Network-with-Cache-Fallback Strategy
Understand how to implement the network-with-cache-fallback strategy in service workers to balance ensuring fresh content and supporting offline access. Learn the approach to fetch from the network first, then use cache as fallback, including dynamic caching and testing methods. This lesson helps you optimize PWA performance for varied network conditions.
We'll cover the following...
How it works
The network-with-cache-fallback strategy, also known as the network-first strategy, is a technique for handling requests in a service worker. Implement it using the following steps:
- Listen to requests in the service worker’s
fetchevent. - Send the request to the network.
- Return it to the requester if the network response is received successfully.
- Search for the request in the cache and return the response if available—if the network request fails.
The slides below illustrate the steps to implement this strategy.
Advantages
This strategy takes advantage of both the network and cache, utilizing the cache only when necessary, such as when there is no network access.
It also means that online users get the most up-to-date content, but offline users get an older cached version. However, we can update the cache entry if the network request ...