A Service Worker is a background script (separate from the main browser thread) that acts as a proxy between your web app and the network.
It allows you to:
- Intercept and handle network requests.
- Cache files and serve them offline.
- Enable push notifications and background sync.
- Make web apps behave like native apps (fast, offline-capable).
👉 Think of it as a programmable network proxy that lives in the browser.
⚙️ Key Features
- Runs in the background (doesn’t need the web page open).
- Intercepts network requests and decides:
- Fetch from network
- Or fetch from cache
- Can work offline (because it caches assets).
- Supports push notifications & background sync.
- Isolated: no direct DOM access (communicates via
postMessage).
📝 Life Cycle of a Service Worker
- Register → Tell the browser about your service worker.
- Install → Cache necessary files.
- Activate → Take control of the app.
- Fetch → Intercept requests and serve responses.
📝 Example: Basic Service Worker Setup
1. Register in your JS file
if ("serviceWorker" in navigator) {
navigator.serviceWorker.register("/service-worker.js")
.then((reg) => {
console.log("Service Worker registered:", reg.scope);
})
.catch((err) => {
console.error("Service Worker registration failed:", err);
});
}
2. Create service-worker.js
// Install event (cache files)
self.addEventListener("install", (event) => {
console.log("Service Worker installing...");
event.waitUntil(
caches.open("v1").then((cache) => {
return cache.addAll([
"/",
"/index.html",
"/styles.css",
"/app.js",
]);
})
);
});
// Activate event
self.addEventListener("activate", (event) => {
console.log("Service Worker activated!");
});
// Fetch event (serve cached files if offline)
self.addEventListener("fetch", (event) => {
event.respondWith(
caches.match(event.request).then((response) => {
return response || fetch(event.request);
})
);
});
✅ Benefits of Service Workers
- Offline browsing (caching HTML, CSS, JS, images).
- Faster page loads (serve assets from cache).
- Push notifications (engage users like native apps).
- Background sync (send data when network is available).
- Key for Progressive Web Apps (PWAs).
⚠️ Limitations
- Works only on HTTPS (secure context), except on localhost.
- Runs in background, so no direct DOM access.
- Requires proper caching strategy to avoid serving stale data.
🔑 Difference Recap
- Web Worker → Run heavy JS tasks in background (performance).
- Service Worker → Control network requests, caching, offline support (PWA features).