reactjsprogressive-web-appsservice-workerworkboxservice-worker-config

Update cache file if last modified is changed in service worker


Is there any way to update file(s) in the service worker if the last modified date time is changed? I have some images that change every 2-3 days and want to let the service worker know to update them.

I separated these images in the cache directory in the service worker as well.

registerRoute(
  ({ url }) => url.origin === self.location.origin && url.pathname.startsWith("/images/changing-images/"),
  new StaleWhileRevalidate({
    cacheName: `changing-images-${cacheSuffix}`,
    matchOptions: {
      ignoreSearch: true,
      ignoreVary: true,
    },
  })
);

Solution

  • You can update resources in self.caches whenever you want, and you can do this from the service worker context, or a page https://developer.mozilla.org/en-US/docs/Web/API/caches.

    Entries in the cache API are Responses, which include headers. The header that's probably most useful to you here is Last-Modified, but it'll only be there if your server chooses to send it.

    Assuming it does, you could implement what you want by checking entries in the caches when your page loads:

    1. Get the cache where images are stored using self.caches.open.
    2. Get all the items in the cache via cache.matchAll. This will give you Responses.
    3. Look at the headers in those Responses. If their Last-Modified date is over a threshold of your choosing, use cache.add to update the cache.