Web Worker API
The Worker API allows JavaScript to run scripts in the background, independently of the main execution thread. This helps keep web pages responsive by performing heavy computations without blocking the UI.
Workers run in a separate thread, cannot directly access the DOM, but can communicate with the main thread via messages.
Key Concepts
- Web Worker: A JavaScript file executed in a background thread.
- Main Thread: The usual execution context of your webpage.
- Communication: Uses
postMessage()
and themessage
event. - Use Cases: Heavy computations, fetching large data, real-time processing.
Creating a Worker
Web Workers allow you to run JavaScript in the background, separate from the main thread, so your web page stays responsive during heavy computations.
1. Separate JS File
You create a dedicated worker file (worker.js
) with the code to run in the background. The main script (main.js
) communicates with the worker using postMessage
to send data and onmessage
to receive results.
worker.js
// Worker code
self.onmessage = function(e) {
const result = e.data * 2; // Example computation
postMessage(result);
};
main.js
const worker = new Worker("worker.js");
// Send data to worker
worker.postMessage(10);
// Receive data from worker
worker.onmessage = function(e) {
console.log("Result from worker:", e.data); // 20
};
2. Inline Worker (Using Blob)
You can also create a worker directly in the main script using a Blob
, which allows small or dynamic worker scripts without a separate file.
const blob = new Blob([`
self.onmessage = function(e) {
postMessage(e.data + 5);
};
`], { type: "application/javascript" });
const worker = new Worker(URL.createObjectURL(blob));
worker.postMessage(10);
worker.onmessage = e => console.log("Inline worker result:", e.data); // 15
Worker Methods & Properties
- postMessage(data) – Send data to the worker.
- terminate() – Stop the worker immediately.
- onmessage – Event handler for receiving messages.
- onerror – Event handler for errors in the worker.
worker.terminate(); // Stops the worker
Communication Between Main Thread and Worker
Web Workers communicate with the main thread using messages. The main thread can send data to the worker using postMessage
, and the worker can send results or updates back using postMessage
.
Main Thread → Worker
The main thread sends data or instructions to the worker:
worker.postMessage("Hello Worker");
Worker → Main Thread
The worker sends data back to the main thread:
postMessage("Hello Main Thread");
Handling Messages
Both the main thread and the worker use onmessage
to receive messages and handle the data appropriately. This allows smooth two-way communication without freezing the page.
// Main thread
worker.onmessage = (e) => console.log("Worker says:", e.data);
// Worker
self.onmessage = (e) => {
console.log("Main thread says:", e.data);
postMessage("Message received");
};
Example: Heavy Computation
The main thread remains responsive while the computation runs in the worker.
// worker.js
self.onmessage = function(e) {
let sum = 0;
for(let i = 0; i < e.data; i++) sum += i;
postMessage(sum);
};
// main.js
const worker = new Worker("worker.js");
worker.postMessage(100000000); // Heavy computation
worker.onmessage = e => console.log("Sum:", e.data);
Advantages
- Prevents UI freezing for heavy operations.
- Allows parallel execution in the browser.
- Simple communication with
postMessage()
.