Web Workers let you run JavaScript in background threads, separate from the main UI thread. This helps you perform heavy or CPU-intensive tasks without blocking the page or making it feel slow and unresponsive.
They are ideal for tasks like data processing, image manipulation, and real-time calculations, where performance and responsiveness are both important.
postMessage() and received with onmessage.A worker is created by instantiating the Worker constructor and passing the URL of the worker script file:
// main.js
const worker = new Worker("worker.js");
Use postMessage() to send data to the worker and onmessage to receive data back from the worker.
worker.postMessage(data) — send data from main thread to worker.onmessage = (event) => {"{"} ... {"}"} — handle incoming messages.This example shows a main script sending a number to the worker. The worker doubles the value and sends the result back.
// main.js
const worker = new Worker("worker.js");
// Send data to the worker
worker.postMessage({ num: 10 });
// Receive data from the worker
worker.onmessage = function(event) {
console.log("Result from worker:", event.data);
};
// Optional: handle errors
worker.onerror = function(error) {
console.error("Worker error:", error.message);
};
// worker.js
onmessage = function(event) {
const input = event.data.num;
const result = input * 2; // heavy computation placeholder
postMessage(result); // send result back to main thread
};
Workers do not automatically stop when your task is done. You should terminate them to free up memory and system resources.
// main.js
const worker = new Worker("worker.js");
// After some time or when the task is done
worker.terminate(); // stops the worker from the main thread
// worker.js
onmessage = function(event) {
// do some work
// ...
// stop the worker from inside the worker file
close();
};
new Worker("worker.js").worker.postMessage().onmessage handler.postMessage().worker.onmessage and updates the UI or logs it.worker.terminate() or close().Because the work happens in a background thread, the main UI thread remains smooth: scrolling, clicking buttons, and typing input stay responsive.
structuredClone() or transferable objects (like ArrayBuffer) for complex data when needed.