Update the service worker and the scripts imported with importScripts

If you change the Javascript code of a service worker, the browser may not  apply the update immediately (as we have already discussed).

In order for the update to take effect you need to:

  1. Change some code inside the main service worker (if you only change code inside a script imported with importScripts the browser will not detect the change)
  2. Visit a page of the website (that activates the service worker or calls serviceWorker.register) and refresh that page
  3. Now the new service worker is installed, but it can’t be activated until you terminate the previous service worker: close and reopen the browser

If a user doesn’t visit your website, the browser will try to fetch a new version of the service worker automatically every 24 hours.

Note that scripts imported with importScripts are cached by the browser and even if you have updated the main service worker they may not get updated. In order to force the update of the imported scripts add a query string to the imported script path.

For example, if you have the following line inside your service worker:

importScripts('https://pushpad.xyz/service-worker.js');

You can force the update of the service worker and its dependency by adding an arbitrary query string (e.g. v2, v3, v4… or anything else – the query string ?foobar would have the same effect):

importScripts('https://pushpad.xyz/service-worker.js?v2');

Note that this behavior will be fixed in the future and you can expect easier updates. However, on April 2017, you still need to use this hack.

Leave a Reply

Your email address will not be published. Required fields are marked *