Service Workers
Service Workers run in the background, separate from the main thread. They are the foundation of Progressive Web Apps (PWAs), enabling offline support, asset caching, background sync, and push notifications.
What is a service worker?
A service worker is a script the browser runs in the background, separate from your page, that can intercept network requests. It's what makes offline support, caching strategies and push notifications possible for Progressive Web Apps. Register one with navigator.serviceWorker.register("/sw.js"); it only works on HTTPS or localhost.
// main.js
if ("serviceWorker" in navigator) navigator.serviceWorker.register("/sw.js");
// sw.js: cache-first for static assets
self.addEventListener("fetch", (event) => {
event.respondWith(
caches.match(event.request).then((hit) => hit || fetch(event.request))
);
});SW Lifecycle
- 1Download: Browser downloads sw.js when navigator.serviceWorker.register() is called
- 2Install: install event fires; use e.waitUntil(cache.addAll([...])) to pre-cache assets
- 3Waiting: New SW waits for existing SW to release all clients; call skipWaiting() to skip
- 4Activate: activate event fires; clean up old caches; call clients.claim() to take control
- 5Fetch: SW intercepts requests with e.respondWith(…) — apply caching strategy here
Caching Strategies
Return cached response if available; fetch and cache on miss. Best for versioned static assets.
Always try the network; fall back to cache if offline. Best for API data that must be fresh.
Immediately return cache; update cache in background. Best for non-critical UI assets.
Only serve from cache. Used for pre-cached assets where network should never be consulted.
Never cache. Best for non-GET requests like POST/PUT that must hit the server.
What Service Workers Can Do
Serve assets from cache when there's no network
Display notifications via PushManager even when app is closed
Retry failed requests when connectivity is restored
Periodically refresh data in the background
Cache shell assets on install for instant loads
Modify, redirect, or mock any HTTP request
Common Pitfalls
Service Worker Demo
Code Editor
<p>Service workers need their own file and HTTPS, so this preview shows the code and checks support.</p>
<pre>// main.js
navigator.serviceWorker.register("/sw.js");
// sw.js: cache-first strategy
self.addEventListener("fetch", (event) => {
event.respondWith(
caches.match(event.request).then((hit) => hit || fetch(event.request))
);
});</pre>
<p id="out"></p>Preview
Service Workers — step by step
Registration and Scope
A service worker is registered by calling navigator.serviceWorker.register with a script URL. Its scope determines which pages it controls — by default everything under the script's directory. Only HTTPS (or localhost) is supported.
🎯 Quick Check
What does a service worker intercept to enable offline support?
Service Workers: summary
Key points
- Lifecycle: install, then activate, then control pages. A new version waits until all old tabs close, unless you call
skipWaiting(). - Service workers can't access the DOM; they communicate with pages via
postMessage. - Workbox provides ready-made caching strategies (cache-first, network-first, stale-while-revalidate).
- A buggy service worker can serve stale files; always version your caches.
Frequently asked questions
›What is the difference between a service worker and a web worker?
A web worker runs heavy computations for one page. A service worker sits between all your pages and the network to handle caching, offline support and push.