eleventy
eleventy copied to clipboard
in search of the perfect service worker
Implementing a good service worker has been one of the most difficult things I have done recently. I wanted a service worker that:
- Caches all assets
- Caches the first page of the site
- Only caches other pages when they are visited
- Detects a new build of the site and starts with a fresh cache so a simple browser refresh gets all the updates
That last one was really hard to achieve, but I believe I have done it. I'd love to get feedback on my implementation.
My .eleventy.js file writes the file service-worker-data.json that contains an array of the file paths to be cached initially and a timestamp for the build. The file paths include all the assets and the path to the first page.
My service worker does nothing for the "install" event.
The "activate" event handler reads the service-worker-data.json file, determines the cache name to use incorporating the build timestamp, deletes any old caches, and then caches the specified files in the new cache.
Maybe you have seen examples where the files to be cached are cached in the "install" event handler. This did not work for me and here's the key! If you do it there and it is not your first load of the site, those files will already be in a cache with an older timestamp. When you cache them in the new cache, it will merely copy them from the old cache and not get new versions from the network. This is why I wait to cache the files in the new cache until I have already deleted the old caches.
You can see all the details at https://mvolkmann.github.io/blog/pwa/.
Is this the perfect service worker or can it be improved?