service-workerbrowser-cache

What happens when you add a version/hash to your service worker file?


I think it is a bad idea to use cache busting for your service worker by adding a version string to its file name. This is never mentioned in any tutorial and I've never seen this method out there in the wild.

You should rather use the no-cache directive and the max-age field in the response header for the service worker file.

But since I did not find a dedicated statement regarding this method I tried it out and it seems like if you change the service worker file it is hard to get rid of the old one. So I can see both files in the sources tab of the dev-tools.

Sources: two SW files

But you won't see the new service worker in the application tab immediately, so I'm not sure, what hinders the new SW to get in charge and what it is actually waiting for.

New SW (renamed!) awaits installation

Does anybody know, how browsers usually handle this situation?


Solution

  • Here's some guidance suggesting why that should be avoided:

    Avoid changing the URL of your service worker script

    If you've read my post on caching best practices, you may consider giving each version of your service worker a unique URL. Don't do this! This is usually bad practice for service workers, just update the script at its current location.

    It can land you with a problem like this:

    1. index.html registers sw-v1.js as a service worker.
    2. sw-v1.js caches and serves index.html so it works offline-first.
    3. You update index.html so it registers your new and shiny sw-v2.js.

    If you do the above, the user never gets sw-v2.js, because sw-v1.js is serving the old version of index.html from its cache. You've put yourself in a position where you need to update your service worker in order to update your service worker. Ew.