Web Workers (Background Threads)
Web Workers run JavaScript in a background thread — preventing heavy computations from freezing the UI. Use them for data processing, image manipulation, file parsing, and any CPU-intensive work.
Web Workers
- new Worker('worker.js') — Creates a background thread running worker.js
- postMessage(data) — Send data to/from worker (serialized/cloned)
- onmessage — Receive messages: worker.onmessage = (e) => console.log(e.data)
- No DOM access — Workers can't access document, window, or DOM. Pure data processing
- terminate() — Kill worker: worker.terminate()
- Use cases — Heavy math, sorting large datasets, image processing, CSV/JSON parsing, encryption
Web Workers Code
// Main thread — creating and using a worker
// === worker.js (separate file) ===
// self.onmessage = function(event) {
// const { numbers } = event.data;
//
// // Heavy computation in background
// const sum = numbers.reduce((acc, n) => acc + n, 0);
// const avg = sum / numbers.length;
// const sorted = [...numbers].sort((a, b) => a - b);
//
// // Send result back
// self.postMessage({ sum, avg, sorted });
// };
// === main.js ===
// const worker = new Worker("worker.js");
//
// // Send data to worker
// const bigArray = Array.from({ length: 1000000 }, () => Math.random() * 1000);
// worker.postMessage({ numbers: bigArray });
//
// // Receive result (UI stays responsive!)
// worker.onmessage = (event) => {
// console.log("Sum:", event.data.sum);
// console.log("Average:", event.data.avg);
// console.log("UI was NOT blocked during computation!");
// };
//
// worker.onerror = (error) => {
// console.error("Worker error:", error.message);
// };
// Inline Worker (no separate file needed)
function createInlineWorker(fn) {
const blob = new Blob([`self.onmessage = ${fn.toString()}`],
{ type: "application/javascript" });
return new Worker(URL.createObjectURL(blob));
}
// Demo: simulate heavy computation
function heavyCompute(numbers) {
console.time("Heavy computation");
const result = numbers.reduce((acc, n) => acc + Math.sqrt(n), 0);
console.timeEnd("Heavy computation");
return result;
}
const testData = Array.from({ length: 100000 }, (_, i) => i);
console.log("Result:", heavyCompute(testData));
console.log("This blocked the UI! Web Workers prevent this.");Tip
Tip
Move CPU-intensive tasks like image processing, data parsing, and complex calculations to Web Workers. The main thread stays free for user interactions, preventing the 'page unresponsive' dialog.
Workers run in background threads. No DOM access. Use for heavy computation. SharedWorker for tabs.
Common Mistake
Warning
Workers can't access the DOM. They run in a separate thread without window, document, or any DOM APIs. Compute data in the worker, then send results back to the main thread for DOM updates via postMessage.
Practice Task
Note
Web Workers: (1) Create a worker that calculates prime numbers. (2) Show a progress indicator on the main thread. (3) Compare UI responsiveness with and without the worker.
Quick Quiz
Key Takeaways
- Web Workers run JavaScript in a background thread — preventing heavy computations from freezing the UI.
- new Worker('worker.js') — Creates a background thread running worker.js
- postMessage(data) — Send data to/from worker (serialized/cloned)
- onmessage — Receive messages: worker.onmessage = (e) => console.log(e.data)