Lesson 1 of 9 · 24m
Service Workers: Lifecycle Before Caching
A service worker is a versioned, event-driven network proxy — and most production pain comes from misunderstanding install, activate, and update.
The first service worker I shipped made a staging deploy look successful while users kept running last week's JavaScript for two days. The code compiled. The cache was warm. The bug was lifecycle: the new worker installed politely and then waited for every existing tab to close, exactly as specified. Service workers are not magic offline spray. They are a separate JavaScript runtime with a versioned deployment pipeline.
A proxy outside the page
A service worker sits between the page and the network for its scope. It can intercept navigation and subresource requests, synthesize responses, cache assets, receive push events, and keep a small amount of work alive after pages close.
// /sw.js
const VERSION = "assets-v18";
const ASSETS = ["/", "/app.css", "/app.js", "/offline.html"];
self.addEventListener("install", event => {
event.waitUntil(caches.open(VERSION).then(cache => cache.addAll(ASSETS)));
});
self.addEventListener("fetch", event => {
if (event.request.mode === "navigate") {
event.respondWith(fetch(event.request).catch(() => caches.match("/offline.html")));
}
});Registration is explicit and scoped:
if ("serviceWorker" in navigator) {
navigator.serviceWorker.register("/sw.js", { scope: "/" });
}The lifecycle is the product
A new worker enters install, then waiting, then activate only after old clients are gone. That conservative default prevents one browser tab from yanking storage and code versions out from under another tab mid-session. It also means deploying a worker is not the same as users running it.
skipWaiting() and clients.claim() shorten that handoff, but they do not make versioning disappear. A page can still be controlled by an old worker while talking to assets cached by a new one. If your schema or asset contract changes, coordinate migration in the page after receiving a controllerchange message; do not assume activation is atomic across open tabs.
Updates are byte-compared
Browsers check the worker script on navigation and roughly every 24 hours. A changed byte triggers the update pipeline, which is why teams hash or version imported scripts carefully. The common production pattern is: HTML network-first, immutable static assets cache-first, API responses application-specific.
Field notes
updatefoundandreg.waitingare how you show "reload for the new version"; do not force reload during form entry.- Service workers require HTTPS except on localhost, and they do not run in every private browsing configuration.
- DevTools lie less if you check "Update on reload" while developing — but remember that users will not have it checked.
- Never cache authenticated API responses unless you can name exactly who may read them later on that device.
Was this lesson helpful?