Skip to content

Service workers

Published Updated

A service worker is a script the browser runs in its own worker thread, separate from any page, which can intercept network requests from the pages it controls and answer them itself. This supports offline use and instant repeat loads. It also enables push. The worker keeps running after the tab is gone.

It has no DOM access, and it only runs in a secure context (HTTPS, or localhost during development).

Register it from the page:

if ('serviceWorker' in navigator) {
navigator.serviceWorker.register('/sw.js');
} else {
// No service worker: the site still works, it just has no offline layer.
}

In /sw.js, answer requests from a cache, falling back to the network:

self.addEventListener('fetch', (event) => {
event.respondWith(
caches.match(event.request).then((hit) => hit || fetch(event.request)),
);
});

The registration and fetch handler form a working service worker. You can add precaching and cache expiry to this implementation. You can also add an update strategy.

A registered worker is installed, then activated, and only then does it start controlling pages. A page loaded before the worker activated stays uncontrolled until it is reloaded. When you ship a new sw.js, the browser installs it alongside the old one and leaves it waiting until the old worker releases its clients, which is why a deploy does not take effect on the very next reload unless you ask it to.

See Service worker lifecycle and The update flow and skipWaiting.

  • A worker at /js/sw.js controls only /js/. Serve it from the root, or send Service-Worker-Allowed. See Registration and scope.
  • After a deploy, users keep the old version while the new worker waits behind it.
  • A cache-first strategy on HTML keeps users on an old page. Choose a strategy for each request type; see Caching strategies.
  • Debug the worker in its own DevTools pane; its lifecycle is separate from page code. See Debugging service workers.

← Back to the Reference overview.