cachingfetchservice-workerservice-worker-events

What does stale-while-revalidate cache strategy mean?


I am trying to implement different cache strategies using ServiceWorker. For the following strategies the way to implement is completely clear:

  1. Cache first
  2. Cache only
  3. Network first
  4. Network only

For example, while trying to implement the cache-first strategy, in the fetch hook of the service-worker I will first ask the CacheStorage (or any other) for the requested URL and then if exists respondWith it and if not respondWith the result of network request.

But for the stale-while-revalidate strategy according to this definition of the workbox, I have the following questions:

  1. First about the mechanism itself. Does stale-while-revalidate mean that use cache until the network responses and then use the network data or just use the network response to renew your cache data for the next time?
  2. Now if the network is cached for the next time, then what scenarios contain a real use-case of that?
  3. And if the network response should be replaced immediately in the app, so how could it be done in a service worker? Because the hook will be resolved with the cached data and then network data could not be resolved (with respondWith).

Solution

    1. Yes, it means exactly that. The idea is simple: respond immediately from the cache, then refresh the cache in the background for the next time.

    2. All scenarios where it is not important to always get the very latest version of the page/app =) I'm using stale-while-revalidate strategy on two different web applications, one for public transportation services and one for displaying restaurant menu information. Many sites/apps are just fine with this but of course not all.

    One very important thing to note here on the #2: You could eg. use stale-while-revalidate only for static assets. This way your html, js, css, images etc. would be cached and quickly served to the user, but the data fetched dynamically from an API could still be fresh. For some apps this works, for some others not so well. Depends completely on the app. Of course you have to remember not to change the semantics of your API if the user is running a previous version of the app etc.

    1. Not possible in any automatic way. What you could do, however, is implement a msg channel between the Service Worker and the "regular JS code on the page" using window.postMessage API. You could listen for certain messages on the page and then, from the Service Worker, send a msg when an important change has happened and the cache has been updated. Then you could either show the user a prompt telling that the page really needs to be reloaded right now or even force reload it from JS. You would need to put this logic of determining when an important update has happened into the Service Worker of course.