Skip to main content
AllDevToolsHub
Back to Glossary

Service Worker

A script that your browser runs in the background, separate from a web page, enabling features that don't need a web page or user interaction.

Detailed Explanation

Service Workers act as a programmable proxy between your web app and the network. They can intercept network requests, cache responses, and serve content even when the user is offline. This is the core technology behind offline-first applications and PWAs. Because they run in the background, they can also handle background sync and push notifications.

Quick Summary

A service worker is a script the browser runs in the background, scoped to your site's origin. It intercepts network requests, manages caches, and can deliver push notifications, the core engine behind offline support and PWAs.

Key Takeaways

Key Takeaways

  • Service workers run on a separate thread with no DOM access and no window or document.
  • Their lifecycle has three phases: install, activate, and fetch, each must be handled correctly to update reliably.
  • Scope is determined by the location of the SW script, a script at /sw.js controls the entire origin.
  • Updates are not automatic for already-open tabs; clients.claim and skipWaiting are needed to take control quickly.
  • Service workers require HTTPS (localhost excepted) and a registered scope.
Use Cases

When to use it

  • Caching the app shell and assets so a PWA loads instantly on repeat visits.
  • Offline-first apps that queue requests and replay them when connectivity returns (background sync).
  • Push notifications driven by a server using the Web Push protocol.
  • Per-route routing strategies (stale-while-revalidate, network-first, cache-first) for fine-grained performance tuning.
Watch out

Common Mistakes

  • Caching index.html with cache-first and shipping a broken update because the SW never lets users see the new shell.
  • Forgetting to call event.waitUntil() in install/activate handlers, the SW may be killed before async work finishes.
  • Putting business logic that depends on the DOM inside the SW, it has no DOM.
  • Hardcoding cache names without versioning, leaving stale assets after a deploy.
FAQ

Service Worker, Frequently Asked

Can a service worker run when the browser is closed?

Briefly, for push notifications and periodic background sync. It is not a long-lived daemon, the browser kills it aggressively to save resources.

Does a service worker replace a CDN?

No, but it complements one. A CDN reduces latency before bytes hit the device; a service worker eliminates the network entirely for cached resources. Together they give the fastest perceived performance.

How do I update a service worker?

Change any byte of the SW script file. The browser detects the change on the next page load and installs the new version in the background. To activate immediately, call self.skipWaiting() during install and clients.claim() during activate.