Web Workers are a way to run JavaScript in the background (on a separate thread) without blocking the main UI thread.
Normally, JavaScript in browsers runs on a single thread (the main thread) – the same thread that updates the UI, handles events, animations, etc.
If you run heavy tasks (like image processing, large calculations, or API data parsing) on the main thread, the browser may freeze or feel laggy.
👉 Web Workers solve this problem by allowing you to offload those heavy tasks to background workers.
⚙️ Key Features
- Run JavaScript code in the background.
- Do not block the main UI thread.
- Communicate with the main thread via messages.
- Can perform long-running tasks (e.g., computations, data processing).
- No access to DOM directly (they can’t manipulate HTML elements).
📝 Example: Using a Web Worker
1. Create a worker file (worker.js)
// worker.js
self.onmessage = function (event) {
console.log("Message from main script:", event.data);
// Example: heavy computation (summing numbers)
let sum = 0;
for (let i = 0; i < 1000000000; i++) {
sum += i;
}
// Send result back
postMessage(sum);
};
2. Use it in your HTML/JS
<!DOCTYPE html>
<html>
<head>
<title>Web Worker Example</title>
</head>
<body>
<h2>Web Worker Demo</h2>
<button id="start">Start Worker</button>
<p id="result"></p>
<script>
let worker;
document.getElementById("start").onclick = function () {
if (window.Worker) { // check browser support
worker = new Worker("worker.js");
worker.postMessage("Start calculation"); // send message to worker
worker.onmessage = function (event) {
document.getElementById("result").innerText =
"Result: " + event.data;
};
} else {
alert("Web Workers are not supported in your browser!");
}
};
</script>
</body>
</html>
🔑 How communication works
postMessage()→ sends data between main script and worker.onmessage→ receives data.- Workers run in isolation (separate scope).
✅ When to use Web Workers
- Heavy computations (mathematical calculations, crypto).
- Processing large data (like CSV/JSON files).
- Image/video processing.
- Running background timers or polling APIs.
- Keeping UI smooth and responsive during heavy tasks.
⚠️ Limitations:
- Cannot access DOM or
windowdirectly. - Can’t use
alert()orconfirm(). - Communication is via message passing only.