What are Web Workers?
Web Workers run JavaScript on a background thread, so heavy work doesn't freeze the UI on the main thread.
Separate thread — workers can't touch the DOM, but can do calculations, parsing, or network work.
Messaging — the main thread and worker communicate by passing messages (postMessage / onmessage).
Use for CPU-heavy tasks like image processing or large data parsing, to keep the page responsive.
// main.js
const worker = new Worker('worker.js');
worker.postMessage({ type: 'compute', data: [1, 2, 3, 4, 5] });
worker.onmessage = (event) => {
console.log('Result:', event.data); // { sum: 15, average: 3 }
};
worker.onerror = (error) => {
console.error('Worker error:', error.message);
};
// worker.js
self.onmessage = (event) => {
const { type, data } = event.data;
if (type === 'compute') {
// CPU-intensive work (does not block main thread)
const sum = data.reduce((a, b) => a + b, 0);
const average = sum / data.length;
self.postMessage({ sum, average });
}
};
// Inline worker (no separate file)
const blob = new Blob([`
self.onmessage = (e) => {
const result = heavyComputation(e.data);
self.postMessage(result);
};
`], { type: 'application/javascript' });
const inlineWorker = new Worker(URL.createObjectURL(blob));The main thread creates a Worker and communicates via postMessage/onmessage. The worker processes data in a separate thread (no UI blocking). Results are sent back via postMessage.
The inline worker creates a worker from a Blob without a separate file. Workers cannot access the DOM — all UI updates must happen on the main thread.
Workers run in a separate thread (no DOM access). Communication via postMessage (structured clone of data).
Know the three types: Dedicated (per-page), Shared (cross-page), Service (offline/caching). The inline Blob worker avoids a separate file.