What is a Service Worker? Lifecycle, Caching and Limits

A service worker is a script that sits between a web page and the network. Learn its lifecycle, caching patterns, limits and common mistakes.

What is a service worker?

A service worker is a JavaScript file that the browser runs in the background, separate from the page, and that can intercept network requests from pages in its scope. MDN describes service workers as acting like proxy servers between the web application, the browser and the network. Because it can answer requests from a cache, a service worker makes offline use and instant repeat loads possible. It is the foundation of progressive web apps.

How it works

The page registers the worker with navigator.serviceWorker.register('/sw.js'). The worker then moves through a lifecycle:

  1. Install. Fired when the browser finds a new worker file. Workers usually create a cache here and store the assets the app needs offline.
  2. Waiting. If an older worker is still controlling open pages, the new one waits. It activates only when no page uses the old version, unless it calls skipWaiting().
  3. Activate. A good moment to delete old caches. A first-time worker does not control already-open pages until they reload, unless it calls clients.claim().
  4. Fetch and other events. The worker handles fetch events and decides what to return with respondWith(). It can also receive push messages and background sync events.
  5. Update. The browser re-fetches the worker file on navigation to an in-scope page, and also when an event fires and the file has not been checked in the last 24 hours. A changed file installs as a new version.

Two constraints matter in practice. A service worker only runs in a secure context, meaning HTTPS (localhost counts as secure for development). And it runs in a worker context: no DOM access, and no synchronous XHR or Web Storage. Pages talk to it with postMessage(). The browser can stop an idle worker, which is why work that must finish is wrapped in event.waitUntil().

Common caching patterns

  • Cache first, network fallback. Return the cached copy if there is one, otherwise fetch. Good for fingerprinted CSS, JS and fonts.
  • Network first, cache fallback. Try the network, serve the cache when offline. Good for HTML that should be fresh.
  • Stale while revalidate. Answer from the cache now, refresh the cache in the background. Good for content where slightly old is acceptable.
  • Offline fallback. When the request is not cached and the network fails, return a prepared offline page instead of an error.
  • Navigation preload. Start the network request in parallel with worker start-up so the worker does not add latency to navigations.

Example

A news site pre-caches its app shell (HTML skeleton, CSS, JS) in the install event. On each request the worker serves static assets cache first and article pages network first, falling back to the last cached copy offline. When the team ships a new sw.js with a v2 cache name, the activate handler deletes the v1 cache.

Common mistakes

  • Caching HTML cache first with no way out. Users keep seeing the old page until the worker updates. Use network first for documents and version your caches.
  • Forgetting waitUntil(). The worker can be stopped before the cache write finishes.
  • Not cloning responses. A response body can be read once, so clone it before caching and returning it.
  • Using skipWaiting() without thought. A new worker can take over a page that was loaded with the old assets.
  • Caching API responses or authenticated pages carelessly. A worker cache does not follow HTTP freshness rules by itself; you decide expiry. See API caching for the header side.
  • Ignoring the first visit. Registering and installing a worker costs bandwidth and CPU before any repeat-visit benefit exists.

Service workers, caching layers and performance

A service worker is one layer among several. The browser HTTP cache follows Cache-Control headers, a CDN serves shared copies from the edge, and the worker's Cache API storage is controlled by your own code. A web worker is a different thing: it moves computation off the main thread but does not intercept requests. In a single-page app, a worker that caches the app shell can make repeat loads fast. The effect shows up in the metrics of Core Web Vitals only when pages are served from the cache, so measure it instead of assuming it: compare repeat visits with real user monitoring, and track lab scores over time with scheduled Lighthouse audits. Caches also change what a performance test measures, as covered in our guides on load testing progressive web apps and cache invalidation in performance testing. For the full API, see MDN's Service Worker API reference.

FAQ: Service Workers

Do I need a service worker?

Only if you want offline support, push notifications or programmatic control of caching. A site that already loads fast and has few returning visitors may gain little for the added complexity.

What is the difference between a service worker and a web worker?

A web worker runs scripts on a background thread so heavy computation does not block the page. A service worker sits between the page and the network, can answer requests from a cache, and lives beyond a single page view.

Why does my new service worker not take effect?

The new version installs but waits until no open page is using the old one. Close all tabs, or call skipWaiting() and clients.claim() if you accept the trade-offs.

Does a service worker need HTTPS?

Yes. Service workers are available only in secure contexts. Browsers also treat http://localhost as secure so you can develop locally.

Can a service worker see or change the page DOM?

No. It has no DOM access and runs on a different thread. It exchanges messages with pages through postMessage().

How do I get rid of a broken service worker?

Ship a replacement sw.js that clears its caches in the activate event, or unregister it from the page. Plan this kill switch before you ship, because a worker that caches HTML can keep serving stale pages.

How fast is your website?

Elevate its speed and SEO seamlessly with our Free Speed Test.

Free Website Speed Test

Analyze your website's load speed and improve its performance with our free page speed checker.