What workbox strategy is used for precached assets

2019-07-31 13:45发布

问题:

I'm trying to understand workbox and service-workers.

What is the workbox strategy used for precached assets when using the workbox-webpack-plugin and GenerateSW mode? ie. cacheFirst, staleWhileRevalidate, etc. Because it seems that I do not have set up a route/strategy for precached assets in order for the service-worker to update the caches for these assets. So what is the default handler for these?

And secondly, how do the Cache-Control headers from the server response play a role in the workbox strategy to refresh the assets? If at all.

Answering the question wrt the root /index.html asset would be most helpful to me.

Thanks.

回答1:

workbox-webpack-plugin generates a service worker that makes a call to workbox.precaching.precacheAndRoute([...]), with an array of URLs (and optional revision information for each URL).

The call to precacheAndRoute() does two things:

  • Precaches all of the URLs provided.

  • Automatically creates a fetch handler for you that will check incoming requests to see if it matches a precached URL, and if so, respond with what's effectively a cache-first strategy. (This is the and route portion.) The code that gets invoked when there's a match isn't literally workbox.strategies.cacheFirst(), but it's roughly equivalent.

Workbox will automatically avoid the browser's HTTP cache if there is out-of-band revision information provided for a given entry in the precache manifest—it uses that as a signal that the contents of the URL might change over time. The docs for the workbox-precaching module shed some more light as to what's going on.