Skip to content
Tutorials Center
My learning

Topics

Lesson 12 of 37 ยท Service Workers

Install and Activate Events

Walk through the service worker lifecycle: the install event, precaching with waitUntil, the waiting phase, skipWaiting, the activate event, clients.claim and cache cleanup.

A service worker goes through distinct phases, and your code hooks into two of them: install and activate. Install is where you prepare (usually by caching files). Activate is where you take over and clean up (usually by deleting old caches). Between them, a new worker may have to wait for the old one to finish. Understanding this dance explains almost every "why is my old version still showing" question.

The lifecycle at a glance

stateDiagram-v2
  [*] --> Installing: register()
  Installing --> Installed: install event succeeded
  Installing --> Redundant: install failed
  Installed --> Activating: no old worker in control, or skipWaiting()
  Installed --> Installed: waits while old worker controls pages
  Activating --> Activated: activate event done
  Activated --> Redundant: replaced by a newer worker

"Installed" is also called "waiting". A worker stays there while pages are still controlled by the previous version.

The install event

install fires once per worker version, right after the script is downloaded and parsed. Use it to download and cache everything the app needs to run offline.

JavaScript
const CACHE = 'shell-v1';
const SHELL = ['/', '/styles.css', '/app.js', '/offline.html'];

self.addEventListener('install', (event) => {
  event.waitUntil(
    caches.open(CACHE).then((cache) => cache.addAll(SHELL))
  );
});

event.waitUntil(promise) tells the browser: the install is not finished until this promise settles. If it rejects, the install fails, the worker becomes redundant and the old worker (if any) keeps running. That is a feature: a half-cached update never goes live.

Two details about cache.addAll:

  • It is atomic: if any single request fails (404, network error), the whole call rejects and nothing is added. One typo in the list breaks the entire install.
  • It fetches with the HTTP cache rules. If a file can be served from the browser's HTTP cache, addAll may store that stale copy. For versioned precaching, request files with cache: 'reload' or use hashed file names (see the precaching lesson).

The waiting phase

If a worker is already active and controlling open pages, the new worker finishes installing and then waits. It does not activate while old-version pages are open, because it could break them (imagine the new worker deleting a cache that old pages still need). When all tabs using the old worker are closed or navigate away, the new one activates.

That is why "I deployed a fix but I still see the old site" is so common: the user has one tab open and never closed it. You can see the waiting worker in DevTools Application > Service workers, with a "skipWaiting" link.

skipWaiting

self.skipWaiting() tells a waiting worker to activate immediately.

JavaScript
self.addEventListener('install', (event) => {
  event.waitUntil(
    caches.open(CACHE).then((c) => c.addAll(SHELL)).then(() => self.skipWaiting())
  );
});

Be careful: with skipWaiting the new worker takes control of pages that were loaded with the old HTML and scripts. If the new worker's caches or responses are incompatible with the old page (for example a changed API for the shell), things can break. Safer approaches: only call skipWaiting when the user chooses to refresh (lesson on updates), or design assets so old and new versions can coexist.

The activate event

activate fires when the worker takes over. The usual job is cache cleanup. Old versions' caches stay on disk until you delete them.

JavaScript
self.addEventListener('activate', (event) => {
  event.waitUntil(
    caches.keys().then((names) =>
      Promise.all(
        names
          .filter((name) => name !== CACHE)
          .map((name) => caches.delete(name))
      )
    )
  );
});

Cleaning in activate (not in install) is important: while the new worker waits, the old worker still needs its own caches.

clients.claim

A freshly activated worker does not control already-open pages, including the one that registered it. self.clients.claim() takes control immediately:

JavaScript
self.addEventListener('activate', (event) => {
  event.waitUntil(self.clients.claim());
});

On a first visit, this means the page is controlled without a reload. On updates, it makes the new worker control tabs that were opened under the old one, with the same compatibility caution as skipWaiting. Many apps use the pair skipWaiting + clients.claim for simple, self-contained sites, and avoid it for complex apps.

You can also enable navigation preload in activate to start the network request in parallel while the worker boots, which helps network-first navigations:

JavaScript
self.addEventListener('activate', (event) => {
  event.waitUntil(self.registration.navigationPreload?.enable());
});

Putting it together

A complete, conservative lifecycle for a worker:

JavaScript
const VERSION = 'v3';
const CACHE = `app-${VERSION}`;
const SHELL = ['/', '/styles.css', '/app.js', '/offline.html'];

self.addEventListener('install', (event) => {
  event.waitUntil(caches.open(CACHE).then((c) => c.addAll(SHELL)));
});

self.addEventListener('activate', (event) => {
  event.waitUntil(
    caches.keys().then((keys) =>
      Promise.all(keys.filter((k) => k.startsWith('app-') && k !== CACHE).map((k) => caches.delete(k)))
    )
  );
});

Note the k.startsWith('app-') guard: on a shared origin (for example several apps under one domain), do not delete caches that belong to something else.

Simulating the lifecycle

The runnable stand-in below models registrations, waiting workers and the effect of skipWaiting and clients.claim. Change the useSkipWaiting flag and watch when the new version takes over.

JS Stand-in: lifecycle with and without skipWaiting

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

No output.

The "warning" line in the second run is the risk of skipWaiting: a page built for v1 is now served by v2.

Cache name versioning in code

Another common helper builds cache names from a version and filters the stale ones. Test your own naming rules here:

JS Which caches would activate delete?

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

No output.

analytics-sdk is kept because it does not belong to this worker.

Common mistakes

  • Putting waitUntil around nothing: forgetting to pass the promise, so install ends early.
  • Listing files that 404 in addAll, which fails the whole install.
  • Deleting all caches in install, breaking the old worker while the new one waits.
  • Assuming skipWaiting is free of risk.
  • Forgetting clients.claim and wondering why the first load is not controlled.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What happens if the promise passed to event.waitUntil() in the install event rejects?

    A failed install means the new version never goes live.
  2. 2. Why delete old caches in activate instead of install?

    Until activation the old worker controls pages and still relies on its own caches.
  3. 3. What does self.skipWaiting() do?

    It ends the waiting phase.
  4. 4. What does clients.claim() do in activate?

    It takes control of already-open pages, including the one that registered the worker.
  5. 5. Why can a single wrong URL in cache.addAll() break a worker?

    A rejected addAll rejects the install promise, so the install fails.

Summary

  • install fires once per version: cache the shell with event.waitUntil(cache.addAll(...)).
  • A new worker waits while pages use the old one; skipWaiting() ends the wait, with some risk.
  • activate is the place to delete old caches and, optionally, call clients.claim().
  • A rejected install promise keeps the old worker; addAll is all-or-nothing.
  • Prefix cache names so you only delete what you own.

Next: The Fetch Event and respondWith