Concept Explanation
Imagine a "Waiter" that stands between your website and the Internet.
- When the website asks for an image, the waiter checks if they already have it in their "Pocket" (The Cache).
- If they do, they give it to you instantly without even checking the internet.
- If they don't, they go to the Internet, get it, and save a copy for next time.
A service worker is a script that runs on its own thread, with no DOM and no window. It keeps running after every tab is closed, and the browser can stop and restart it whenever it likes. Those two facts explain most of its odd rules: you cannot touch the page directly, and you cannot keep anything in a module-level variable and expect it to still be there next time.
Its scope is the folder it is served from. A worker at /js/sw.js only controls /js/, which is why it almost always belongs at the site root.
Syntax or Core Structure
Registering the Worker
if ('serviceWorker' in navigator) {
window.addEventListener('load', () => {
navigator.serviceWorker.register('/sw.js');
});
}
Inside sw.js (The Waiter)
self.addEventListener('fetch', (event) => {
event.respondWith(
caches.match(event.request).then((response) => {
// If found in cache, return it. Otherwise, go to network.
return response || fetch(event.request);
})
);
});
The install and activate pair
const VERSION = 'v3';
const PRECACHE = ['/', '/offline.html', '/app.css', '/app.js'];
self.addEventListener('install', (event) => {
event.waitUntil(
caches.open(VERSION).then((cache) => cache.addAll(PRECACHE))
);
self.skipWaiting(); // do not sit in 'waiting' forever
});
self.addEventListener('activate', (event) => {
event.waitUntil(
caches.keys().then((keys) => Promise.all(
keys.filter((k) => k !== VERSION).map((k) => caches.delete(k))
)).then(() => self.clients.claim())
);
});
Key Features
- Lifecycle:
install(pre-cache) thenactivate(clean up old caches) thenfetch(intercept every request in scope). - The waiting state: a new worker installs but does not take over while an old one still controls an open tab.
skipWaiting()plusclients.claim()shortcuts that. event.waitUntil()keeps the worker alive until your promise settles. Without it the browser may kill it mid-write.event.respondWith()must be called synchronously inside the fetch handler, though it may be given a promise.
Real World Example
A newsroom that must work on the subway. The install step pre-caches the shell: HTML frame, CSS, fonts, logo, and an offline fallback page. The fetch handler serves articles network-first so readers get fresh news, and falls back to the cached copy when the train enters the tunnel. Readers notice nothing except that the app never shows the dinosaur.
Common Mistakes
- Caching the HTML document aggressively. Users get pinned to a build from three deploys ago. Cache the shell by version and revalidate the document.
- Never cleaning old caches. Storage grows until the browser evicts everything at once, usually at the worst moment.
- Forgetting the response is single-use. You must
response.clone()before both caching it and returning it, or one of the two gets an already-consumed body. - Intercepting non-GET requests.
POSTcannot be cached; let those pass straight through. - Debugging with a stale worker. Use "Update on reload" in DevTools, or you will spend an afternoon editing a file the browser is ignoring.
- Assuming module-scope state persists. The worker is terminated aggressively. Persist anything that matters into Cache Storage or IndexedDB.
Best Practices
- Version your cache name and delete every other cache in
activate. - Serve the worker from the root so its scope covers the whole site.
- Guard the fetch handler: skip cross-origin requests and non-GET methods explicitly.
- Prefer Workbox for anything real. Hand-written workers are a good way to learn and a poor way to ship.
- Give yourself a kill switch: a worker that unregisters itself, so a bad deploy is recoverable.
Practice Exercises
- The Auditor: Open Chrome DevTools, go to the "Application" tab, and click on "Service Workers." Can you see any running on your current page?
- The Lifecycle: Research the "Install" and "Activate" events in a Service Worker. Why do we usually use these events to "Pre-cache" files?
- The Offline Challenge: Build a site that displays a specific "Oops, you're offline!" page using a Service Worker whenever the network fails.