Lesson 8 of 9
Web Workers (Background Processing)
Web Workers run JavaScript in a background thread, separate from the main UI thread. Heavy computations (data processing, image manipulation, sorting large arrays) can run in a Worker without freezing the page or blocking user interactions. Workers communicate with the main thread via message passing.
Web Worker Architecture
Web Workers run in a separate thread:
Main Thread (UI) Worker Thread (Background)
โโโ DOM access โ
โโโ DOM access โ
โโโ UI rendering โ
โโโ Heavy computation โ
โโโ postMessage() ----โ โโโ onmessage (receives)
โโโ onmessage (receives) โ---- postMessage()
โโโ User interactions โโโ Data processing
Usage:
1. const worker = new Worker('worker.js');
2. worker.postMessage(data); - Send data to worker
3. worker.onmessage = (e) => { /* handle result */ };
In worker.js:
self.onmessage = (e) => {
const result = heavyCalculation(e.data);
self.postMessage(result);
};
Workers CANNOT:
โข Access the DOM (no document, no window)
โข Access parent scope variables directly
Workers CAN:
โข fetch() API, setTimeout, IndexedDB
โข Run CPU-intensive tasks without blocking UI
Web Workers run intensive computations on background threads to keep UI fluid
Finished this lesson?