JavaScriptHard
What are Web Workers and how can they be used to improve performance?
By FrontendPro Editorial Team Updated 8/8/2026
#JavaScript
Answer
Web Workers are a way to run JavaScript in the background, separate from the main execution thread of a web application. This helps in performing heavy computations without blocking the user interface. You can create a Web Worker using the Worker constructor and communicate with it using the postMessage and onmessage methods.
js
// main.js
const worker = new Worker("worker.js");
worker.postMessage("Hello, worker!");
worker.onmessage = function (event) {
console.log("Message from worker:", event.data);
};
// worker.js
onmessage = function (event) {
console.log("Message from main script:", event.data);
postMessage("Hello, main script!");
};
