Hint
Run JS in a background thread — no DOM access; use postMessage to communicate
Web Workers run JavaScript in a separate background thread — preventing heavy computation from blocking the main thread (UI freezing).
// main.js
const worker = new Worker('worker.js');
// Send data to worker (structured clone — copies data)
worker.postMessage({ array: bigArray, threshold: 50 });
// Receive results
worker.onmessage = (e) => {
console.log('Result:', e.data.result);
worker.terminate(); // clean up
};
worker.onerror = (e) => console.error('Worker error:', e.message);
// worker.js — completely separate context
self.onmessage = (e) => {
const { array, threshold } = e.data;
// Heavy computation — won't block UI
const result = array.filter(x => x > threshold).reduce((a,b) => a+b, 0);
self.postMessage({ result });
};
Limitations: No access to DOM, window, document. Communication only via postMessage. Data is copied (structured clone), not shared (except SharedArrayBuffer).
Use cases: Image/video processing, data parsing, crypto, ML inference, large sort/filter operations.