Clean β’ Professional
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.
postMessage() and the message event.Web Workers allow you to run JavaScript in the background, separate from the main thread, so your web page stays responsive during heavy computations.
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
};
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.terminate(); // Stops the 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");
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");
};
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);
postMessage().