Skip to content

Service Worker

A JavaScript file that runs in a background thread, intercepting network requests from the page. The foundation of offline support, push notifications, and background sync in modern web apps.

A Service Worker is a script the browser runs in a background thread, separate from the main page. It can intercept every network request the page makes via the fetch event, choose to serve from cache vs network vs both, and respond with whatever it wants -- enabling offline support, custom routing, and the "app shell" architecture that powers most PWAs.

Lifecycle (simplified):

  1. Register -- the page calls navigator.serviceWorker.register('/sw.js'). The browser downloads the script and installs it (calling the install event handler if any).
  2. Activate -- once installed and any old service worker is gone, the new one activates and starts intercepting fetches.
  3. Fetch -- every network request from the controlling page fires a fetch event the worker can intercept.

Capabilities a service worker enables:

  • Offline / poor-network UX: precache app-shell assets at install time, serve them from cache on subsequent visits.
  • Push notifications: receive push messages from a server while the page is closed (subject to user permission).
  • Background sync: defer state-changing requests until network returns.
  • Custom caching strategies: stale-while-revalidate, cache-first-then-network, etc.

Constraints worth knowing:

  • Service workers ONLY work on HTTPS (and localhost).
  • They run in a separate global context with NO access to window, document, or DOM. Communication with the page happens via postMessage / Broadcast Channel.
  • Worker upgrades are sticky: a new worker waits to activate until all controlled tabs close. self.skipWaiting() and clients.claim() skip this, but read the docs first.
  • Debugging: Chrome DevTools > Application > Service Workers shows registered workers, their state, and lets you trigger updates / clear cache.

Worth flagging: navigator.serviceWorker.register(...) in the page bundle ONLY proves the registration is attempted. The worker may fail to install, fail to control any clients, or do nothing useful. BeaverCheck's PWA-depth check surfaces the registration call as a positive signal but doesn't (yet) probe the worker's behavior.

Related terms

Further reading

Send Feedback