Browser InternalsIntermediate
What is a Web Worker and what can it be used for?
Why do we need Web Workers?
JavaScript is single-threaded — JS execution, DOM operations, and rendering all happen on the main thread. A long-running computation blocks the main thread, causing the page to freeze and become unresponsive.
Web Workers let you run JavaScript on a background thread, keeping the main thread free.
Characteristics
- Runs on a separate background thread, in parallel with the main thread
- Cannot access the DOM (
document,window, etc.) - Communicates with the main thread via
postMessage/onmessage(structured clone) - Can use:
fetch,indexedDB,console,setTimeout,WebSocket,Crypto, etc.
Basic usage
Main thread (main.js)
const worker = new Worker('worker.js');
// Send data to the worker
worker.postMessage({ data: [1, 2, 3, 4, 5] });
// Receive the result
worker.onmessage = (e) => {
console.log('Worker returned:', e.data);
};
worker.onerror = (e) => {
console.error('Worker error:', e.message);
};
Worker thread (worker.js)
self.onmessage = (e) => {
const result = heavyCompute(e.data.data);
self.postMessage(result);
};
function heavyCompute(arr) {
return arr.reduce((acc, n) => acc + n * n, 0);
}
Inline Worker (no separate file needed)
const blob = new Blob([`
self.onmessage = (e) => {
self.postMessage(e.data * 2);
};
`], { type: 'application/javascript' });
const worker = new Worker(URL.createObjectURL(blob));
worker.postMessage(21);
worker.onmessage = (e) => console.log(e.data); // 42
Common use cases
| Use case | Examples |
|---|---|
| Heavy computation | Encryption/decryption, image processing, matrix operations |
| Data parsing | Parsing large CSV / JSON files |
| WebAssembly | Running WASM modules off the main thread |
| Background sync | Coordinating with Service Workers for offline sync |
| Real-time data | Processing WebSocket streams, updating charts |
Types of workers
| Type | Description |
|---|---|
| Dedicated Worker | One-to-one; serves only the page that created it |
| Shared Worker | Shared by multiple pages of the same origin |
| Service Worker | Special worker for cache interception, push notifications, and offline support |
Important notes
- Data passed to/from a worker is copied (structured clone by default). Use Transferable Objects (e.g.
ArrayBuffer) for zero-copy transfers of large data. - Call
worker.terminate()when done to free resources. - Synchronous APIs such as
localStorageare not available inside a worker.
✦ AI Mock Interview
Type your answer and get instant AI feedback
Sign in to use AI scoring
