Service Workers
Build an accurate mental model of what the browser does, from navigation and HTTP through parsing, rendering, storage, workers, security, and DevTools, so you can predict behavior and debug real pages.
What you will be able to do
#- Describe the service worker lifecycle.
- Choose a caching strategy for a request type.
- Explain scope and update behavior.
Overview
#A service worker is a script that runs in the background and can intercept network requests.
Lifecycle
- Register with
navigator.serviceWorker.register('/sw.js'). - Install event: precache assets. A failed install aborts activation.
- Activate event: clean old caches.
- Fetch event: respond to requests from cache, network, or a strategy.
A new service worker waits until all clients using the old one are gone, unless it calls skipWaiting() and clients call clients.claim().
Strategies
- Cache first: fast, good for versioned assets.
- Network first: fresh, good for APIs.
- Stale while revalidate: serve cache, update in the background.
Scope
A service worker at /sw.js controls the whole origin. At /app/sw.js it controls only /app/. Scope cannot be widened beyond the script location without a Service-Worker-Allowed header.
Caution
Service workers only run on https or localhost, and a buggy one can serve stale content until it is unregistered.
Questions to carry forward
- Which strategy fits a versioned asset?
- How do you force an update safely?
- Why can a service worker serve stale content?
Exercises
#Reference answers and expected output are authored, not executed in this browser. Nothing you type is run, and there is no Run or Pass control on this page.
Exercise 1Predict
A service worker at /app/sw.js is registered from /app/index.html. Which requests can it intercept?
Exercise 2Implement
Write a fetch handler that serves versioned assets cache-first and falls back to the network.
starter.javascriptself.addEventListener('fetch', (event) => { // TODO });Reveal the reference answer
reference.javascriptself.addEventListener('fetch', (event) => { event.respondWith( caches.match(event.request).then((cached) => cached || fetch(event.request)) ); });Authored expected output: Cached responses are returned first; misses go to the network.
caches.match resolves to a cached response or undefined, and the fallback fetches from the network on a miss.
Common misconceptions
#- A service worker can access the DOM.
- skipWaiting takes effect immediately without client claims.
- A service worker controls the whole origin regardless of its path.
Follow-up practice
#- browser-internals-web-workers
- browser-internals-devtools-elements-network
Your progress
#Answers, drafts and completion marks are stored only in this browser. Nothing is sent to a server and no account is used.
Verification: authored. Answers and outputs on this page are authored reference material, not executed results.