Updating the service worker

Are you stuck with an old version of the service worker or your imported scripts are not being updated as you expect? This guide shows you how to ensure that your service worker and the imported scripts are updated in a timely manner.

Follow these steps in order to update a service worker:

  1. Trigger one of the following events in order to start the update process:
    • Open your website (and navigate to a page inside the scope of the service worker)
    • Send a push message (or trigger another event like sync); in this case the update runs only if there wasn’t an update check in the previous 24 hours
    • Call serviceWorker.register() with a new URL
  2. The browser tries to download the new service worker and the imported scripts; however the requests may not be sent directly to your server; instead the requests go through the normal HTTP cache; for this reason make sure that you employ at least one of the following strategies:
    • Use navigator.serviceWorker.register('/service-worker.js', { updateViaCache: 'none' }) in order to tell the browser to skip the HTTP cache for the service worker and for all the imported scripts
    • Set the HTTP header Cache-Control: max-age=0 when you serve your service worker and your scripts
  3. The new service worker is installed but it is not active yet; use one of the following strategies to activate it:
    • You can simply close (and reopen) your website
    • You can call self.skipWaiting()

Leave a Reply

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