RainingChain
RainingChain

Reputation: 7746

How to update service workers?

Situation:

On mywebsite.com/game, I registered a service-worker with

navigator.serviceWorker.register('/service-worker.js', {scope: "/"});

On my server, '/service-worker.js' has a maxAge of 1d.


Problem:

service-worker.js has a major bug. It always displays an empty page and can't fetch anything. service-worker.js must be changed.

The problem is whenever a user goes to mywebsite.com/game, it displays the empty page and does nothing more. I am unable to make the client fetch the new service-worker.js.

How can I make the client fetch the new service-worker.js?

Upvotes: 13

Views: 19254

Answers (3)

Péter Magyar
Péter Magyar

Reputation: 71

Close your page and open it again. Source

The accepted answer does not provides any working solution.

Upvotes: 0

andrew_jackson
andrew_jackson

Reputation: 123

Just add ?v=1 to your script like this.

navigator.serviceWorker.register('/service-worker.js?v=1', {scope: "/"});

And increment the number of script version when you make changes of service worker's script

Upvotes: -1

Jeff Posnick
Jeff Posnick

Reputation: 56044

What you're describing—a check for updates to /service-worker.js—happens by default, automatically, under the circumstances laid out in this article:

An update is triggered if any of the following happens:

  • A navigation to an in-scope page.
  • A functional events such as push and sync, unless there's been an update check within the previous 24 hours.
  • Calling .register() only if the service worker URL has changed. However, you should avoid changing the worker URL.

All modern web browsers will ignore any Cache-Control headers you set on /service-worker.js by default and go directly against the web server to obtain the latest copy.

This Stack Overflow answer has some best practices for what the revised service-worker.js file should contain if you want it to behave like a "kill switch."

Upvotes: 17

Related Questions