Service Workers and PWAs
Published by Brayan K
A service worker is a background script that the browser runs separately from your web page, acting as a programmable network proxy that can cache responses and serve your app offline — the foundation of Progressive Web Apps (PWAs).
Part of the free JavaScript course at LearnCodingFast — hands-on lessons with examples you run in your browser, plus practice exercises and a quick quiz.
Registration, activation and control are different milestones
A service worker is an event-driven worker associated with an origin and scope. It cannot read the page DOM and is not a permanently running background process. The browser may stop it between events, so global variables are not durable storage. Use HTTPS in deployment; a local loopback development origin is an exception that permits this fixture.
register resolves with a registration, not a guarantee that the current page is controlled. An installed worker may be waiting, an active worker may serve other clients, and navigator.serviceWorker.controller describes this page. ready waits for an active registration for the page; it does not by itself promise immediate control of the current document.
const observations = [
{ registered: true, active: false, controlled: false },
{ registered: true, active: true, controlled: false },
{ registered: true, active: true, controlled: true }
];
for (const item of observations) {
console.log(item.controlled ? "This page is controlled" :
item.active ? "An active worker exists; this page is not controlled" : "Registration is not activation");
}
// ✅ Expected output:
// Registration is not activation
// An active worker exists; this page is not controlled
// This page is controlledThat first program models UI decisions; it does not register a worker. The complete fixture below performs real registration, waits for activation and observes controllerchange. Its activation handler uses clients.claim for eligible open clients. claim does not force a waiting update to skip its waiting phase.
Install a bounded release and clean only caches you own
Call event.waitUntil during install with the promise that prepares required assets. If that preparation rejects, installation fails instead of silently declaring the incomplete release ready. Keep versioned cache names so an old active worker can continue using its own resources while the next release waits.
const prefix = "lcs-sw-lesson-";
const current = "lcs-sw-lesson-v2";
const keys = ["lcs-sw-lesson-v1", "unrelated-app-cache", current];
console.log(keys.filter(key => key.startsWith(prefix) && key !== current).join(", "));
console.log(keys.filter(key => !key.startsWith(prefix)).join(", "));
// ✅ Expected output:
// lcs-sw-lesson-v1
// unrelated-app-cacheCache Storage is shared by scripts on the origin; its names are your organization convention. Never delete every cache except your current one on a site that may have other features. Cleanup belongs in activation after the previous release is no longer needed. The fixture also demonstrates that unregistering a worker and deleting its caches are separate operations.
A cached response is still subject to browser storage limits and user deletion. It is not a permanent backup. Web Storage APIs (localStorage, sessionStorage, IndexedDB) owns client-side retention and storage alternatives.
Specify which requests may receive cached responses
A blanket cache-everything handler can retain private data, replay stale API responses or return HTML for a missing JavaScript file. This fixture permits two public GET paths only, on the same origin and without a query string. Other requests fall through to normal networking. Its static data file is cache-first; its known document navigation is network-first with an offline cache fallback.
function choosePolicy(request, origin) {
if (typeof origin !== "string" || !["http:", "https:"].includes(new URL(origin).protocol) || new URL(origin).origin !== origin ||
!request || typeof request.method !== "string" ||
typeof request.url !== "string" || typeof request.mode !== "string") {
throw new TypeError("request fields and canonical origin required");
}
const url = new URL(request.url);
if (request.method !== "GET" || url.origin !== origin || url.search || url.hash) return "bypass";
if (url.pathname === "/app/data.txt") return "cache-first";
if (url.pathname === "/app/index.html" && request.mode === "navigate") return "network-first";
return "bypass";
}
const origin = "https://lesson.example";
for (const request of [
{ method: "GET", url: origin + "/app/data.txt", mode: "cors" },
{ method: "GET", url: origin + "/app/index.html", mode: "navigate" },
{ method: "POST", url: origin + "/app/data.txt", mode: "cors" },
{ method: "GET", url: origin + "/app/private", mode: "cors" },
{ method: "GET", url: origin + "/app/data.txt?user=1", mode: "cors" }
]) console.log(choosePolicy(request, origin));
// ✅ Expected output:
// cache-first
// network-first
// bypass
// bypass
// bypassfunction choosePolicy(request, origin) {
if (typeof origin !== "string" || !["http:", "https:"].includes(new URL(origin).protocol) || new URL(origin).origin !== origin ||
!request || typeof request.method !== "string" ||
typeof request.url !== "string" || typeof request.mode !== "string") {
throw new TypeError("request fields and canonical origin required");
}
const url = new URL(request.url);
if (request.method !== "GET" || url.origin !== origin || url.search || url.hash) return "bypass";
if (url.pathname === "/app/data.txt") return "cache-first";
if (url.pathname === "/app/index.html" && request.mode === "navigate") return "network-first";
return "bypass";
}
choosePolicy({method: "GET", url: "ftp://lesson.example/app/data.txt", mode: "cors"}, "ftp://lesson.example");
// ✅ Expected error:
// TypeError: request fields and canonical origin requiredrespondWith must be called synchronously during the fetch event, but it can receive a promise for the eventual Response. A network-first catch handles rejected fetches; an HTTP 404 or 500 normally resolves to a Response and needs an explicit response.ok/status policy. This fixture returns those HTTP responses unchanged and falls back only on a rejected navigation request.
const response = new Response("Unavailable", { status: 503 });
console.log(response.ok, response.status);
const result = await Promise.allSettled([Promise.resolve(response)]);
console.log(result[0].status);
// ✅ Expected output:
// false 503
// fulfilledResponse bodies are consumable streams. If a runtime strategy needs both to cache a response and return it, clone it before one consumer reads the body. The fixture pre-caches at installation and does not silently add arbitrary runtime responses. Fetch API owns HTTP success and body consumption.
Run the real three-file fixture through offline use and an update
Create the three paths shown below under one local server root. Serve sw.js as JavaScript and open /app/index.html on localhost. The worker at /sw.js is registered with /app/ scope. The data file contains public tutorial text only. The displayed transcript was captured from the actual browser fixture, including the steps after initial page load.
sw.js — service worker fixture
const CACHE = "lcs-sw-lesson-v1";
const PREFIX = "lcs-sw-lesson-";
const RESOURCES = ["/app/index.html", "/app/data.txt"];
self.addEventListener("install", event => {
event.waitUntil(caches.open(CACHE).then(cache => cache.addAll(RESOURCES)));
});
self.addEventListener("activate", event => {
event.waitUntil((async () => {
const keys = await caches.keys();
await Promise.all(keys.filter(key => key.startsWith(PREFIX) && key !== CACHE)
.map(key => caches.delete(key)));
await self.clients.claim();
})());
});
self.addEventListener("fetch", event => {
const request = event.request;
const url = new URL(request.url);
if (request.method !== "GET" || url.origin !== self.location.origin ||
url.search || !RESOURCES.includes(url.pathname)) return;
if (url.pathname === "/app/data.txt") {
event.respondWith((async () => {
const cache = await caches.open(CACHE);
return (await cache.match(request)) || fetch(request);
})());
} else if (request.mode === "navigate") {
event.respondWith((async () => {
try { return await fetch(request); }
catch (error) {
const cached = await (await caches.open(CACHE)).match("/app/index.html");
if (cached) return cached;
throw error;
}
})());
}
});Serve these three files together on localhost or HTTPS. Open /app/index.html. This fixture is a browser project, not a script for the isolated editor. The transcript also includes the offline and update steps explained below.
app/index.html — service worker fixture
<!doctype html>
<html lang="en">
<head><meta charset="utf-8"><title>Offline fixture</title>
<link rel="icon" href="data:,"></head>
<body><h1>Offline lesson</h1>
<script type="module">
window.fixtureOutput = [];
window.fixtureReady = false;
window.readFixture = async () => {
const response = await fetch("/app/data.txt");
if (!response.ok) throw new Error("fixture request failed");
return response.text();
};
await navigator.serviceWorker.register("/sw.js", { scope: "/app/" });
await navigator.serviceWorker.ready;
if (!navigator.serviceWorker.controller) {
await new Promise(resolve => navigator.serviceWorker.addEventListener(
"controllerchange", resolve, { once: true }
));
}
window.fixtureOutput.push("controlled " + Boolean(navigator.serviceWorker.controller));
window.fixtureOutput.push("initial read " + await window.readFixture());
window.fixtureReady = true;
</script></body></html>Output
controlled true
initial read A cached lesson fixture
offline A cached lesson fixture
offline reload Offline lesson
private unavailable offline
update waiting; both release caches retained
update activated after old client closed
unrelated cache preservedServe these three files together on localhost or HTTPS. Open /app/index.html. This fixture is a browser project, not a script for the isolated editor. The transcript also includes the offline and update steps explained below.
app/data.txt — service worker fixture
A cached lesson fixtureServe these three files together on localhost or HTTPS. Open /app/index.html. This fixture is a browser project, not a script for the isolated editor. The transcript also includes the offline and update steps explained below.
To reproduce the offline steps, wait until fixtureReady is true, then enable offline mode for the page. Call await readFixture(): the data comes from Cache Storage. Reload /app/index.html while offline and confirm its heading. A request to /app/private must fail offline because it was never allowlisted or cached. Re-enable networking before testing the update.
For the update, change lcs-sw-lesson-v1 to lcs-sw-lesson-v2 in sw.js, save it and call update on the /app/ registration. Keep the controlled page open: the new worker installs and waits while both version caches remain. Close all pages controlled by the old worker; the new worker can activate and remove only the old lesson caches. The verification fixture seeds an unrelated cache and checks that it survives.
This release deliberately does not call skipWaiting. A product that offers immediate updates needs an explicit user-facing reload policy and compatible page/worker versions; forcing activation can pair an old page with a new worker. Browsers may also provide developer-tool options that bypass normal lifecycle behavior, so turn those off when testing waiting.
Guided exercise: retain the current release and unrelated caches
Fill the literal hints. Cleanup must use both the owned prefix and the current-version comparison.
const prefix = "lesson-";
const current = "lesson-v2";
const keys = ["lesson-v1", "other-app", current];
const obsolete = keys.___(key => key.___(prefix) && key !== ___); // 👉 replace ___ with filter
// 👉 replace ___ with startsWith
// 👉 replace ___ with current
console.log(obsolete.join(", "));
// ✅ Expected output:
// lesson-v1Build brief: a conservative request-policy boundary
Implement choosePolicy(request, origin). Require string method, url and mode fields, and a canonical HTTP(S) origin string. Parse an absolute request URL. Return bypass for non-GET requests, another origin, query strings, fragments or unlisted paths. Return cache-first for /app/data.txt and network-first only for a navigate-mode /app/index.html request. Everything else remains normal networking.
Keep this pure decision separate from storage and networking. Then apply equivalent decisions in a real fetch handler and test the installed worker, because a passing classifier alone cannot prove offline behavior.
function choosePolicy(request, origin) {
if (typeof origin !== "string" || !["http:", "https:"].includes(new URL(origin).protocol) || new URL(origin).origin !== origin ||
!request || typeof request.method !== "string" ||
typeof request.url !== "string" || typeof request.mode !== "string") {
throw new TypeError("request fields and canonical origin required");
}
const url = new URL(request.url);
if (request.method !== "GET" || url.origin !== origin || url.search || url.hash) return "bypass";
if (url.pathname === "/app/data.txt") return "cache-first";
if (url.pathname === "/app/index.html" && request.mode === "navigate") return "network-first";
return "bypass";
}
const origin = "https://lesson.example";
const cases = [
["GET", origin + "/app/data.txt", "cors"],
["GET", origin + "/app/index.html", "navigate"],
["GET", origin + "/app/index.html", "cors"],
["GET", "https://elsewhere.example/app/data.txt", "cors"],
["GET", origin + "/app/data.txt?x=1", "cors"],
["POST", origin + "/app/data.txt", "cors"],
["GET", origin + "/app/missing.js", "cors"]
];
console.log(cases.map(([method, url, mode]) => choosePolicy({ method, url, mode }, origin)).join(", "));
// ✅ Expected output:
// cache-first, network-first, bypass, bypass, bypass, bypass, bypassTest methods, query strings, cross-origin URLs, exact path matching, missing assets, offline navigation, failed installation and a waiting update. Inspect the actual registration scope and caches in browser developer tools. A manifest, icons and service worker do not form a universal installability guarantee: installation criteria and prompts vary by browser. This lesson verifies offline worker behavior, not installation UI, push delivery or background synchronization.
Practice quiz
What does register resolving establish?
- A registration object is available
- Every current page is controlled
- An update has skipped waiting
- Every asset is cached permanently
Answer: A registration object is available. Registration, activation and page control are separate observations.
What does this complete program print? const k=["app-v1","other","app-v2"];console.log(k.filter(x=>x.startsWith("app-")&&x!=="app-v2").join(","));
- other
- app-v1
- app-v2
- app-v1,other
Answer: app-v1. Only the owned obsolete version is selected.
Which request should this fixture bypass?
- Its allowlisted public GET data file
- An offline navigation to its cached document
- A private API request
- The exact allowed static path
Answer: A private API request. Private responses are outside its public offline contract.
What does this complete program print? const r=new Response("missing",{status:404});console.log(r.ok,r.status);
- true 200
- true 404
- false 200
- false 404
Answer: false 404. HTTP errors still produce responses; check their status explicitly.
What does a normal installed update do while old controlled clients remain?
- Waits while the old worker continues serving them
- Always activates immediately
- Deletes every cache immediately
- Closes all browser tabs
Answer: Waits while the old worker continues serving them. The fixture preserves both release caches through waiting.
What does clients.claim do in this activation handler?
- Forces a waiting worker to skip waiting
- Claims eligible currently open clients after activation
- Makes HTTP origins universally secure
- Guarantees permanent background execution
Answer: Claims eligible currently open clients after activation. It changes client control for an active worker; it is not skipWaiting.
What does this complete program print? console.log(new URL("https://lesson.example/app/data.txt?x=1").search.length>0);
- false
- undefined
- true
- TypeError
Answer: true. The policy rejects query-bearing requests.
Which claim does the real fixture leave unverified?
- A real worker installs
- Cached data works offline
- An update waits for an old client
- Every browser will offer an install prompt
Answer: Every browser will offer an install prompt. Offline checks do not establish cross-browser installation UI.
Continue this course
- Previous: Web Components & Custom Elements
- Next: WebAssembly & JS Interop — Run near-native compiled code and call between WebAssembly and JavaScript
- Quick reference: JavaScript cheat sheet