Skip to content
Tutorials Center
My learning

Topics

Lesson 14 of 37 ยท Service Workers

Service Worker Updates and Versioning

Learn how browsers detect a new service worker, why updates wait, how to version caches, and how to show users an update available prompt safely.

Shipping a normal website update is easy: deploy and everyone gets it on the next load. A PWA is different, because a service worker and its caches deliberately keep serving what they have. If you do nothing, users can run an old version for days. Handling updates well is a core PWA skill: detect the new worker, load it safely, and tell the user when a refresh will bring new code.

How the browser finds an update

When a page in scope loads (a navigation), and at least every 24 hours while the worker is active, the browser re-fetches the service worker script and compares it byte by byte to the installed one. This check happens in the background and ignores the HTTP cache for the main script in current browsers. If a single byte differs, the browser treats it as a new version and starts the install flow of the previous lesson.

Three consequences:

  1. Change the worker file to change the version. Editing the shell files alone (app.js, styles.css) does nothing, because the worker file itself did not change. Include a version number or a build hash in sw.js.
  2. Imported scripts count. Files loaded with importScripts() or ES import are also compared (subject to updateViaCache).
  3. Never cache sw.js for long. Serve it with Cache-Control: no-cache (or max-age=0) so the check always goes to the server.
JavaScript
// sw.js
const VERSION = '2026-11-12.1';   // bump on every release (or inject at build time)
const CACHE = `app-${VERSION}`;

You can force a check yourself:

JavaScript
const reg = await navigator.serviceWorker.getRegistration();
reg?.update();                                   // check now
setInterval(() => reg?.update(), 60 * 60 * 1000);  // hourly for long-lived tabs

The update flow

sequenceDiagram
  participant Page
  participant Browser
  participant Old as Old worker (v1)
  participant New as New worker (v2)
  Page->>Browser: navigation
  Browser->>Browser: fetch sw.js, bytes differ
  Browser->>New: install
  New->>New: cache new shell
  Note over New: waiting, v1 still controls the page
  Page->>New: user clicks Refresh (postMessage SKIP_WAITING)
  New->>Browser: skipWaiting()
  Browser->>New: activate
  Browser->>Page: controllerchange
  Page->>Page: location.reload()

The page decides when to switch, by messaging the waiting worker.

Detecting a waiting worker on the page

The registration fires updatefound when a new worker starts installing. You can watch its state and react when it reaches installed while an old worker still controls the page.

JavaScript
const registration = await navigator.serviceWorker.register('/sw.js');

registration.addEventListener('updatefound', () => {
  const newWorker = registration.installing;
  newWorker.addEventListener('statechange', () => {
    if (newWorker.state === 'installed' && navigator.serviceWorker.controller) {
      showUpdateBanner(newWorker);       // an update is ready
    }
  });
});

function showUpdateBanner(worker) {
  banner.hidden = false;
  refreshButton.onclick = () => worker.postMessage({ type: 'SKIP_WAITING' });
}

let reloading = false;
navigator.serviceWorker.addEventListener('controllerchange', () => {
  if (reloading) return;
  reloading = true;
  location.reload();
});

The navigator.serviceWorker.controller check matters: on the very first install there is no old controller, and no banner should appear.

And the worker side listens for the message:

JavaScript
// sw.js
self.addEventListener('message', (event) => {
  if (event.data && event.data.type === 'SKIP_WAITING') {
    self.skipWaiting();
  }
});

This pattern is safe because the user chooses the moment: the app can warn about unsaved changes first. The reload guard stops an infinite loop when the controller changes more than once.

Modeling the page-side logic

Here is the banner logic as a runnable stand-in, driven by simulated state changes. Try changing the first-install case.

JS Stand-in: when to show the update banner

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Versioning cache names and files

Pair the worker's version with versioned cache names: app-v7. On activate, delete every older app- cache. Within a version, files are fixed. For assets that you update independently (images, data), use separate caches with their own version so you do not re-download the shell when only an image changes.

Content hashes in file names (app.3f9a1c.js) work even better: the file list in the worker changes when the file changes, so the worker script itself changes, triggering the update. Build tools generate this for you.

The next stand-in compares two worker versions' file lists to show which entries to download and which to delete, which is what precaching tools do.

JS Stand-in: diff two precache manifests

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Strategy: how aggressively to update

Approach User experience Risk
Do nothing New version applies after all tabs close Users on stale code for long
skipWaiting + clients.claim automatically Update next load Old page with new worker mismatch
Update banner + user action User controls timing Needs extra UI code
Reload automatically on controllerchange Fast Can lose unsaved work
Check for updates when the tab becomes visible Good for long-lived tabs Slight extra traffic

For apps with forms or editors, the banner approach is best. For content sites, automatic activation is usually fine.

A visibility-based check is easy to add:

JavaScript
document.addEventListener('visibilitychange', () => {
  if (document.visibilityState === 'visible') registration.update();
});

Troubleshooting updates

  • "My change isn't live." Open Application > Service workers. A "waiting" entry shows your update is installed but not active. Click skipWaiting to test.
  • Update never starts. The sw.js response may be cached by a CDN or HTTP cache. Check its Cache-Control header.
  • Install fails. The new version rejected in install (for example a 404 in addAll), so the old one stays. Check the worker's console.
  • User stuck on a broken worker. Ship a fixed version at the same URL; the browser will still check within 24 hours. As a last resort, ship the kill-switch worker from lesson 2 of this chapter.

Do not use a different URL for each deployed worker (sw-v2.js) unless you also update the registration. The browser identifies a registration by scope, and old registrations with a stale script URL keep running.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. How does the browser decide that a service worker has a new version?

    Any byte difference in sw.js (or its imported scripts) counts as an update.
  2. 2. Which Cache-Control is best for sw.js?

    The update check must always reach the server, so avoid long caching of the worker script.
  3. 3. In the update banner pattern, why check navigator.serviceWorker.controller?

    With no controller, the page has no older version to update from.
  4. 4. What is the purpose of the reload guard in the controllerchange handler?

    Without it, the page can enter a reload loop.

Summary

  • Browsers re-fetch sw.js on navigation and about daily; a one-byte change triggers an update.
  • Put a version or hash in the worker and never cache the script for long.
  • A new worker installs, then waits; the page can message it to skipWaiting and reload on controllerchange.
  • Version cache names, delete old ones on activate, and diff precache lists.
  • Choose an update strategy that matches how much unsaved state your app holds.

Next: Cache API Basics