Manage Service Worker Cache

The code for the worker I’m experimenting with now looks like 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' ]); }) ); }); 

Unless, of course, the standard fetch event listener returning from the cache or fires a network request if the item does not exist.

But what if, from the above example, a.js updated only a.js - how can I get a service worker to update this file, but only this file; and how can I ensure that the next time the user views my page, they will not pull out the outdated version of the file from the working one?

The best I can imagine is to add a cache URL to these files, for example

'/react-redux/node_modules/react/dist/react-with-addons.js?hash=1MWRF3...'

then update all the module loaders that I use to request these files with the same current hash cache, and then in the installation event of SW iterate over the current cache keys and delete everything that is outdated and add everything that is missing.

This would seem to solve both problems: when the file is updated, the network request that is sent will not correspond to anything in the current Work Work of the Service, and therefore the same network failure will occur; and selective insertion of the cache in the Service Worker installation event will not try to add things to the cache that already exist and are current.

And, of course, the Service Worker code will change as these hash values ​​change (automatically from the build process), and so getting a SW to reinstall when changing files will also happen.

But I can not help but think about it in a simpler way. There is?

+6
source share
1 answer

Your understanding of what should ideally happen and the difficulties in ensuring an efficient and reliable update of cached assets are accurate.

While you can use your own approach, there are existing tools that automate the fingerprint process of each file, and then generate a worker file that manages your cached assets. I developed one of them, sw-precache . offline-plugin is another alternative that covers a similar framework.

+5
source

Source: https://habr.com/ru/post/1014017/


All Articles