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,
},
})
);
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 Response
s, 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:
self.caches.open
.cache.matchAll
. This will give you Response
s.Response
s. If their Last-Modified
date is over a threshold of your choosing, use cache.add
to update the cache.