2

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?

BairDev
  • 2,865
  • 4
  • 27
  • 50

1 Answers1

4

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.

Jeff Posnick
  • 53,580
  • 14
  • 141
  • 167
  • This section says _sw-v1.js caches and serves index.html so it works offline-first._, but we could create a SW, which uses the _network first policy_ for the `index.html`. In this case we would not run into the deadlock, right? – BairDev Jan 14 '19 at 13:58
  • Also I still would like to understand a bit better the difference in how browsers handle service worker files of the same and of different names. Or is the updating process actually the same? – BairDev Jan 14 '19 at 14:53
  • 3
    Registering a SW file with a different name will trigger a SW update. Changing the contents of a SW file while keeping the same name will also trigger a SW update. It's much simpler to just keep the same name and change the contents of the file, and then you don't have to worry about whether `index.html` is cache- or network-first. – Jeff Posnick Jan 14 '19 at 15:36
  • Although this may be some what off-topic, I think it's worth to mention that `.webmanifest` (or `manifest.json` files should (probably) also not be versioned: https://github.com/w3c/manifest/issues/446#issuecomment-351368893 – Null May 23 '19 at 17:07