The HTML Web Workers API enables web applications to run heavy JavaScript computations—such as data processing, image filtering, and complex calculations—in background threads without blocking the main browser UI loop or freezing user interactions.
Web Workers execute JavaScript files in a separate thread context completely detached from the main window DOM:
// Main Script: Spawn background worker thread
const worker = new Worker("worker.js");
// Send data payload to background worker
worker.postMessage({ number: 42 });
// Receive calculated response from worker
worker.onmessage = (event) => {
console.log("Worker Result:", event.data);
};
Inside worker.js (Worker Thread):
// Background Worker Script
self.onmessage = (event) => {
const result = event.data.number * 2;
self.postMessage(result); // Send answer back
};
Key Web Worker rules:
document, window, or direct HTML DOM nodes.postMessage() and onmessage event listeners.flowchart TD
A["Main Thread (DOM Rendering & User Events)"] -- "worker.postMessage(data)" --> B["Background Worker Thread (Isolated execution context)"]
B -- "Calculates Heavy Logic" --> C["worker.postMessage(result)"]
C --> A
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>HTML Web Workers Demonstration</title>
</head>
<body style="font-family: system-ui, sans-serif; background-color: #0f172a; color: #f8fafc; padding: 2rem;">
<h2>Background Computation Worker</h2>
<div style="background-color: #1e293b; padding: 1.5rem; border-radius: 8px; max-width: 450px;">
<button id="calc-btn" style="background-color: #2563eb; color: white; padding: 10px 16px; border: none; border-radius: 6px; cursor: pointer;">
Start Calculation
</button>
<p id="result" style="margin-top: 1rem; color: #34d399;"></p>
</div>
<script>
const btn = document.getElementById("calc-btn");
const result = document.getElementById("result");
btn.addEventListener("click", () => {
result.textContent = "Calculating in background thread...";
// Inline Web Worker blob script
const code = `
self.onmessage = function() {
let total = 0;
for (let i = 0; i < 1e8; i++) { total += i; }
self.postMessage(total);
};
`;
const blob = new Blob([code], { type: "application/javascript" });
const worker = new Worker(URL.createObjectURL(blob));
worker.postMessage("start");
worker.onmessage = (e) => {
result.textContent = "Final Calculation Total: " + e.data;
worker.terminate(); // Stop worker thread
};
});
</script>
</body>
</html>
worker.terminate() from the main thread or self.close() inside the worker to free up system CPU memory resources.document object; calculate data in the worker and send results back to the main thread to update the DOM.Write a line instantiating a Web Worker from a script file named calculator.js!
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With
Experiment with the code from this lesson in our interactive playground.