Search code examples
webpackworkbox

Workbox Service Worker duplicate loading or not reading from cache?


I have these 2 images here:

enter image description here enter image description here

Is there a reason as to why in the first image, in Google Chrome Inspector Network Tab, that there is two operations for each image:

  1. Fetch from Cache?
  2. XHR from Server?

Does this mean that every time I load this page, I am redownloading the files? Should the application instead just refer to the cache and only download if the file is updated?

Do I have to configure webpack so that my assets use hashes in their name, to help with versioning like my .js files?

edit: This is in development mode, or webpack-dev-server


Solution

  • You're using the StaleWhileRevalidate strategy, which will respond from the cache right away, but automatically perform a fetch() "in the background" to ensure that a given asset is fresh for the next time that it's requested.

    What you're seeing is therefore expected.

    If you go with a scheme that adds hashes to your assets, then using a strategy like CacheFirst is more appropriate, since you'll know that if you have an entry in the cache for a given URL, it's always going to correspond to the exact content you're expecting. The one additional thing that you'd want to do in that case, though, is to put some sort of upper bound on your cache sizes, via workbox.expiration, so that you don't end up storing an ever-increasing number of old versions of the same asset.