DOM & Browser APIs

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

  1. 1
    Download: Browser downloads sw.js when navigator.serviceWorker.register() is called
  2. 2
    Install: install event fires; use e.waitUntil(cache.addAll([...])) to pre-cache assets
  3. 3
    Waiting: New SW waits for existing SW to release all clients; call skipWaiting() to skip
  4. 4
    Activate: activate event fires; clean up old caches; call clients.claim() to take control
  5. 5
    Fetch: SW intercepts requests with e.respondWith(…) — apply caching strategy here

Caching Strategies

Cache-first

Return cached response if available; fetch and cache on miss. Best for versioned static assets.

Network-first

Always try the network; fall back to cache if offline. Best for API data that must be fresh.

Stale-while-revalidate

Immediately return cache; update cache in background. Best for non-critical UI assets.

Cache-only

Only serve from cache. Used for pre-cached assets where network should never be consulted.

Network-only

Never cache. Best for non-GET requests like POST/PUT that must hit the server.

What Service Workers Can Do

Offline support

Serve assets from cache when there's no network

Push notifications

Display notifications via PushManager even when app is closed

Background sync

Retry failed requests when connectivity is restored

Periodic sync

Periodically refresh data in the background

Precaching

Cache shell assets on install for instant loads

Request interception

Modify, redirect, or mock any HTTP request

Common Pitfalls

SW only works on HTTPS (or localhost) — HTTP sites cannot register service workers
Serve your app over HTTPS in production. localhost is whitelisted for development.
Forgetting to version your cache name — old cached files serve after deploy
Increment the cache name (e.g. 'v2') in the activate event and delete the old cache
Caching POST requests or auth-sensitive endpoints with cache-first strategy
Use network-first or network-only for dynamic API requests; cache only static assets
Not calling skipWaiting() / clients.claim() — users see the old version until they close all tabs
Call self.skipWaiting() in install and self.clients.claim() in activate to activate immediately

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

1 / 4
1

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.

1 of 4
🔍Service Workers Persist Across Navigations
A service worker runs in its own thread, separate from any page. It stays alive between page loads and can handle push events and background sync even when the user has closed all tabs of your site. Updates only take effect after all controlled tabs are closed and the new worker activates.

🎯 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.