Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Managing Service Worker cache

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?

like image 393
Adam Rackis Avatar asked Jan 12 '17 15:01

Adam Rackis


1 Answers

Your understanding of what should ideally happen, and the difficulties in making sure that cached assets are updated efficiently and reliably, is spot-on.

While you could roll your own approach, there are existing tools that will automate the process of fingerprinting each file and then generating a service worker file that manages your cached assets. I've developed one of them, sw-precache. offline-plugin is another alternative that covers similar ground.

like image 186
Jeff Posnick Avatar answered Sep 21 '22 15:09

Jeff Posnick