Web Workers
Offload heavy computations from the main thread
What are Web Workers?
Web Workers enable multithreaded JavaScript execution by running scripts in background threads. This protects the UI from freezing during intensive tasks like data processing, cryptography, or large calculations.
Parallel Execution
How Web Workers Work
1. Worker Creation
Create a Worker with the new Worker() constructor using a separate script file.
const worker = new Worker('worker.js');
2. Message Passing
Use postMessage() to send data between main thread and workers.
worker.postMessage({ data: 'payload' });
worker.onmessage = function(e) { ... };
3. Thread Isolation
Workers cannot access DOM or synchronous APIs, ensuring thread safety.
Shared memory available with caution
Ideal Use Cases
- Data intensive calculations
- Audio/video processing
- Machine learning inference
- Heavy cryptographic operations
Performance Benefits
Before Workers
Main thread blocked for 3000ms
With Workers
UI remains responsive
Basic Implementation
Main Thread (worker.js)
const worker = new Worker('worker.js');
worker.postMessage({
command: 'calculate',
numbers: [2, 3, 5, 7]
});
worker.onmessage = function(event) {
console.log('Result from worker:', event.data);
};
Worker Thread (worker.js)
onmessage = function(e) {
const result = e.data.numbers.reduce(
(acc, val) => acc * val,
1
);
postMessage(result);
};