I created the basic Workbox StaleWhileRevalidate strategy for my favicon and it should return the cached value on the request if network is offline. It works partially. Actually it returns the cached value only for 2 requests and other requests are failing. In the console, we can see errors about unhandled exception and failed to fetch. I'm wondering how it's possible?
The service worker handler.
self.addEventListener('fetch', (event) => {
console.log(5555); // basically works every time
if (event.request.url.indexOf('favicon.ico') !== -1) {
event.respondWith((async () => {
// Configure the strategy in advance.
const strategy = new workbox.strategies.StaleWhileRevalidate({cacheName: 'favicon-cache-v1'});
// Make two requests using the strategy.
// Because we're passing in event, event.waitUntil() will be called automatically.
return strategy.handle({event, request: event.request.url})
.catch(() => {
// it's never happens somehow (propably because it's always fetch from cache, but I'm not sure
console.log("WHOOOPSS, CATCH")
})
})());
}
});
As you can see, there are errors in the console about Failed favicon fetch. But how it's possible? Workbox should catch it, it prints '5555' debug message and it should return the cached favicon for all requests. But it does it only for 2 requests and other requests are failing. Why does it happen?
This is working as expected. The two requests from your client app to the service worker are successful because you have the assets cached. The two requests to update the cached asset from the service worker to the server fail because the network is offline.