The service worker code I'm currently experimenting with looks like this in part
self.addEventListener('install', function(event) {
event.waitUntil(
caches.open('v1').then(function(cache) {
return cache.addAll([
'/react-redux/node_modules/react/dist/react-with-addons.js',
'/react-redux/node_modules/react-dom/dist/react-dom.js',
'/react-redux/a.js'
]);
})
);
});
With of course the standard fetch event listener that returns from cache, or runs a network request if the item is not there.
But what if, from the example above, a.js
, and only a.js
is updated—how do I get the service worker to update that file, but only that file; and how do I ensure that the next time the user browses to my page, they won't pull the now-stale version of the file from the service worker?
The best I can imagine would be to add a cache buster to those file urls, for example
'/react-redux/node_modules/react/dist/react-with-addons.js?hash=1MWRF3...'
then update whatever module loader I'm using to request these files with that same, current hash/cache buster, and then in the SW install event iterate over the current cache keys and delete anything that's stale, and add anything that's missing.
That would seem to solve both problems: when a file is updated, the network request that's sent won't match anything in the now-stale Service Worker, and so the same network fallback will happen; and the selective cache insertion in the Service Worker's install event wouldn't try to add things to the cache that are already there and current.
And of course the Service Worker code would change as these hash values change (automatically from a build process) and so getting the SW to re-install when files change would happen, as well.
But I can't help but think there's a simpler way. Is there?