Web Workers and Service Workers
Understanding browser background processing and caching mechanisms
Web Workers and Service Workers
In this document, I want to explain what Web Workers and Service Workers are, how they work in the browser, and how they differ. After that, I will compare them directly, and then add notes on how they relate to browser caching and React Query caching.
Web Worker
A Web Worker is a JavaScript script that runs in a background thread, separate from the main execution thread (UI thread). Its primary purpose is to handle heavy computations without blocking rendering or user interactions.
Characteristics
- Runs in a background thread
- Cannot directly access the DOM
- Communicates with the main thread using
postMessage
andonmessage
- Terminates when the page is closed
- Has its own event loop and execution context
Use Cases
- Image or video processing
- Cryptographic operations
- Parsing or transforming large datasets
- Any CPU-intensive task that would otherwise freeze the UI
Example
// worker.js
self.onmessage = function (event) {
const result = heavyComputation(event.data);
self.postMessage(result);
};
// main.js
const worker = new Worker("worker.js");
worker.postMessage(inputData);
worker.onmessage = function (event) {
console.log("Worker result:", event.data);
};
Service Worker
A Service Worker is a special type of Web Worker that operates as a programmable proxy between the browser and the network. It can intercept network requests, manage caching, and enable offline capabilities for web applications.
Characteristics
- Runs in the background, independent of any page
- Lives beyond the page lifecycle (remains active after tabs are closed)
- Requires HTTPS for security reasons
- Intercepts network requests via the
fetch
event - Can use Cache API and IndexedDB for storage
Use Cases
- Offline-first Progressive Web Apps (PWAs)
- Asset caching (JavaScript, CSS, images)
- API response caching with custom strategies
- Push notifications
- Background synchronization
Caching Strategies
-
Cache First
- Returns cached response if available
- Falls back to network if not cached
- Risk: users may keep seeing outdated assets after a new deployment
-
Network First
- Tries the network first, then uses cache as fallback
- Ensures data freshness but can be slow on bad connections
-
Stale-While-Revalidate
- Serves cached data immediately for a fast response
- Updates cache in the background with a fresh network response
- Balances speed and freshness
Example
// service-worker.js
self.addEventListener("install", (event) => {
event.waitUntil(
caches.open("app-cache").then((cache) => {
return cache.addAll(["/", "/index.html", "/main.css", "/main.js"]);
})
);
});
self.addEventListener("fetch", (event) => {
event.respondWith(
caches.match(event.request).then((response) => {
return response || fetch(event.request);
})
);
});
Registered in a React app:
// index.js
import ReactDOM from "react-dom/client";
import App from "./App";
import * as serviceWorkerRegistration from "./serviceWorkerRegistration";
ReactDOM.createRoot(document.getElementById("root")).render(<App />);
// Enable PWA features
serviceWorkerRegistration.register();
Web Worker vs Service Worker
Feature | Web Worker | Service Worker |
---|---|---|
Scope | Background computation | Network proxy and caching |
DOM Access | ❌ Not allowed | ❌ Not allowed |
Lifecycle | Ends when page closes | Independent, persists after page close |
Communication | postMessage with main thread |
postMessage with pages + intercepts fetch |
Use Cases | Heavy calculations | Caching, offline support, push, PWA |
Storage | In-memory only | Cache API, IndexedDB |
Browser Caching vs Service Worker Caching
Browser Caching
- Controlled by server headers (
Cache-Control
,ETag
,Expires
) - Automatic and server-driven
- Limited flexibility from the client side
- May fail when offline
Service Worker Caching
- Fully programmable by developers
- Fine-grained control over caching policies
- Can define custom fallbacks and offline behavior
- Essential for offline-first web applications
React Query vs Service Worker Caching
Although both can cache data, they exist on different layers and serve different purposes.
React Query
- Runs inside the JavaScript runtime of a single page
- Cache is in-memory and tied to the browser tab
- Designed for managing UI state + server state fetching
- Provides policies like
staleTime
andcacheTime
- Automatically revalidates queries when needed
Service Worker
- Operates at the network layer
- Persists cache across sessions using Cache API
- Can cache static assets and API responses
- Useful for offline support and improving perceived performance
Key Difference: React Query optimizes data fetching and UI state inside a running app, while Service Workers handle network requests and offline caching across the entire PWA.