Installation, activation and versioned cleanup
Quick answer
A service worker passes through installation and activation before it can control eligible clients. An update can wait while older clients remain controlled.
How it works
In sw.js, register install and activate event listeners. event.waitUntil(promise) extends the event lifetime for associated asynchronous work. A rejected install promise can cause installation to fail. During activation, remove only outdated caches belonging to this app, not all caches on the origin. skipWaiting() and clients.claim() change update/control timing; use intentionally and account for page/worker version mismatches. The snippets are alternatives for a fresh worker script in the isolated lab; the logs appear in the service worker console, not the page console.
Local examples
Use this as a replacement sw.js in a fresh isolated offline-lab origin; install/activate or request ./v14-message as directed. Observe the worker console. NOT RUN locally.
(async () => {self.addEventListener("install",event=>{event.waitUntil(caches.open("bm-v14-install-demo").then(()=>console.log("prepared")));});})()Expected console output (not executed locally):
preparedThe installation task creates its own cache before its promise fulfills.
Use this as a replacement sw.js in a fresh isolated offline-lab origin; install/activate or request ./v14-message as directed. Observe the worker console. NOT RUN locally.
(async () => {self.addEventListener("activate",event=>{event.waitUntil(Promise.resolve().then(()=>console.log("activated")));});})()Expected console output (not executed locally):
activatedThe activation handler attaches its asynchronous work to the event lifetime.
Common mistakes
Do not put asynchronous installation work outside waitUntil or automatically delete other apps’ caches. Do not treat an update as an atomic switch for all open pages.
Practice
Inspect installing, waiting and active states in a local browser. Plan how versioned assets remain compatible with pages still using an older worker.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Installation, activation and versioned cleanup — Knowledge Check
Apply the concept and reason about local example output.
Which method connects asynchronous setup to the install event lifetime?
Which caches should a version-cleanup routine remove?
Why might a new worker remain waiting after installation?
What is the expected console output of Installation, activation and versioned cleanup example 1?
(async () => {self.addEventListener("install",event=>{event.waitUntil(caches.open("bm-v14-install-demo").then(()=>console.log("prepared")));});})()What is the expected console output of Installation, activation and versioned cleanup example 2?
(async () => {self.addEventListener("activate",event=>{event.waitUntil(Promise.resolve().then(()=>console.log("activated")));});})()