Web Workers are a feature in JavaScript that allow you to run code in the background, on a separate thread from the main UI thread.
They help keep your application responsive by performing heavy or long-running tasks without blocking the user interface.
⚙️ 1️⃣ Why Web Workers Exist
JavaScript is single-threaded — meaning it can only execute one task at a time.
If a heavy operation (like processing large data or images) runs on the main thread, it can cause:
- UI freezing
- Input lag
- “Page unresponsive” warnings
✅ Web Workers fix this by moving those heavy computations to a background thread.
🧩 2️⃣ How Web Workers Work
A Web Worker runs in its own thread, separate from the main one.
It can communicate with the main thread via messages (postMessage and onmessage),
but it cannot directly access the DOM or global window.
Example: Creating a Web Worker
main.js
const worker = new Worker("worker.js");
// Send data to worker
worker.postMessage(1000000000);
// Receive result
worker.onmessage = (e) => {
console.log("Result:", e.data);
};
worker.js
onmessage = function (e) {
let total = 0;
for (let i = 0; i < e.data; i++) total += i;
postMessage(total);
};
✅ The main thread stays responsive while the worker does the heavy computation.
🚫 3️⃣ Limitations
- Cannot access the DOM or
documentdirectly. - Can’t use certain APIs (like
alert()orconfirm()). - Communicates only via message passing (no shared state).
- Extra file loading overhead (workers run in a separate script).
💡 4️⃣ When to Use Web Workers
Use them for CPU-intensive or non-blocking tasks such as:
- Data processing or sorting large arrays
- Image or video manipulation
- Complex mathematical computations
- Background data fetching or caching
- Running AI/ML models in the browser
💬 Example Use Case
// Without a worker - UI freezes
for (let i = 0; i < 1e9; i++) {} // Heavy loop
// With a worker - UI remains smooth
const worker = new Worker("heavyTask.js");
worker.postMessage("start");
💡 In Short:
Web Workers let you run heavy computations in the background without freezing the UI.
They’re ideal for CPU-intensive tasks, improving performance and responsiveness in web applications.