Search code examples
service-workerprogressive-web-appsworkbox

Workbox won't cache dynamically loaded images


I'm trying to create a PWA with workbox. I want it to cache images that are displayed as the result of a rest api call. So I get the links and display the results, but the images are not getting cached by workbox and I don't know why. I'm very new to workbox but I thought the basic concept would be very simple. I have added pre-caching and the following routes:

workbox.routing.registerRoute(
  /\.css$/,
  new workbox.strategies.NetworkFirst()
);

workbox.routing.registerRoute(
  /\.js$/,
  new workbox.strategies.NetworkFirst()
);

workbox.routing.registerRoute(
  /\.(?:png|jpg|jpeg|svg|gif)$/,
  new workbox.strategies.StaleWhileRevalidate()
);

In the network tab of developer tools, I can see that the pre-cached files are marked as "Served from service worker". But the REST images are always loaded over network. The REST images also don't appear in the runtime cache.

How can I get workbox to cache these images too?


Solution

  • The StaleWhileRevalidate Workbox strategy indeed suppose to make the network request each time for each resource, because it is making two requests in parallel from both the cache and the network. So that is why you are seeing those network requests in Chrome Dev Tools. Read more here about this strategy https://developers.google.com/web/tools/workbox/reference-docs/latest/workbox.strategies.StaleWhileRevalidate. So if you want to retrieve the images from the cache only (if they are available there) you can use CacheFirst strategy (https://developers.google.com/web/tools/workbox/reference-docs/latest/workbox.strategies.CacheFirst).

    I also recommend to you to enable Workbox debugging so you know what happening and why in your Service Worker.

    workbox.setConfig({
      debug: true
    });
    

    Hope it will help you!