HTML Web Workers Get Certified
What are HTML Web Workers?
Web Workers let you run JavaScript in a background thread so heavy tasks don’t freeze the page. The main thread stays responsive while the worker does the work.
Key Points
- Workers run in a separate thread and cannot access the DOM directly.
- Communication is done with
postMessage()and theonmessageevent. - Ideal for calculations, data processing, image processing, etc.
- Different from Service Workers (which handle network and caching).
HTML Web Workers Code Examples
1. Basic Web Worker (Inline with Blob)
A simple worker that receives a message and sends a result back.
What this code does: Creates a worker from a Blob (so no external file is needed) and shows the result on the page.
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Basic Web Worker</title>
<style>
body { font-family: Arial, sans-serif; padding: 20px; background: #f5f5f5; }
button { padding: 10px 20px; font-size: 16px; cursor: pointer; }
#result { margin-top: 15px; font-size: 18px; }
</style>
</head>
<body>
<h2>Basic Web Worker</h2>
<button onclick="startWorker()">Start Worker</button>
<p id="result">Click the button to start...</p>
<script>
function startWorker() {
if (!window.Worker) {
document.getElementById("result").textContent = "Web Workers not supported.";
return;
}
// Create worker code as a string
const workerCode = `
self.onmessage = function(e) {
const msg = e.data;
self.postMessage("Worker received: " + msg + " → Done!");
};
`;
// Create a Blob URL so we don't need an external file
const blob = new Blob([workerCode], { type: "application/javascript" });
const worker = new Worker(URL.createObjectURL(blob));
worker.onmessage = function(e) {
document.getElementById("result").textContent = e.data;
worker.terminate(); // clean up
};
worker.postMessage("Hello from main thread");
}
</script>
</body>
</html>
2. Heavy Calculation in a Worker
Run a long loop in the background so the UI stays responsive.
What this code does: Counts to a large number in a worker and reports the result without freezing the page.
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Heavy Calculation Worker</title>
<style>
body { font-family: Arial, sans-serif; padding: 20px; background: #f5f5f5; }
button { padding: 10px 20px; font-size: 16px; margin-right: 10px; cursor: pointer; }
#status { margin-top: 15px; font-size: 18px; }
</style>
</head>
<body>
<h2>Heavy Calculation (Non-Blocking)</h2>
<button onclick="runInWorker()">Run in Worker</button>
<button onclick="runInMain()">Run in Main Thread (will freeze)</button>
<p id="status">Ready</p>
<script>
function runInWorker() {
document.getElementById("status").textContent = "Worker is calculating...";
const workerCode = `
self.onmessage = function() {
let sum = 0;
for (let i = 0; i < 500000000; i++) {
sum += i;
}
self.postMessage(sum);
};
`;
const blob = new Blob([workerCode], { type: "application/javascript" });
const worker = new Worker(URL.createObjectURL(blob));
worker.onmessage = function(e) {
document.getElementById("status").textContent = "Worker finished. Sum = " + e.data;
worker.terminate();
};
worker.postMessage("start");
}
function runInMain() {
document.getElementById("status").textContent = "Main thread calculating (UI may freeze)...";
let sum = 0;
for (let i = 0; i < 500000000; i++) {
sum += i;
}
document.getElementById("status").textContent = "Main thread finished. Sum = " + sum;
}
</script>
</body>
</html>
3. Passing Data to and from a Worker
Send an array to the worker, let it process the data, and receive the result.
What this code does: Worker doubles every number in an array and returns the new array.
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Data Processing Worker</title>
<style>
body { font-family: Arial, sans-serif; padding: 20px; background: #f5f5f5; }
button { padding: 10px 20px; font-size: 16px; cursor: pointer; }
#output { margin-top: 15px; font-size: 16px; background: white; padding: 15px; border-radius: 6px; }
</style>
</head>
<body>
<h2>Process Array in Worker</h2>
<button onclick="processData()">Double the Numbers</button>
<div id="output">Click the button...</div>
<script>
function processData() {
const numbers = [1, 2, 3, 4, 5, 10, 20];
const workerCode = `
self.onmessage = function(e) {
const arr = e.data;
const result = arr.map(n => n * 2);
self.postMessage(result);
};
`;
const blob = new Blob([workerCode], { type: "application/javascript" });
const worker = new Worker(URL.createObjectURL(blob));
worker.onmessage = function(e) {
document.getElementById("output").innerHTML =
"Original: [" + numbers.join(", ") + "]<br>" +
"Doubled: [" + e.data.join(", ") + "]";
worker.terminate();
};
worker.postMessage(numbers);
}
</script>
</body>
</html>
Important Limitations
- Workers cannot access the DOM or the
windowobject. - You must use
postMessageto send data back and forth. - Always call
worker.terminate()when you are finished to free resources.
Web Worker vs Service Worker
- Web Worker – Background computation (CPU-heavy tasks).
- Service Worker – Network proxy, caching, offline support, push notifications.
Web Resources on HTML Web Workers
1. MDN : Using Web Workers
2. MDN : DedicatedWorkerGlobalScope
Questions and Answers related to HTML Web Workers
A Web Worker is a JavaScript script that runs in a background thread. It allows heavy calculations to happen without blocking the main UI thread.
Use const worker = new Worker("worker.js") or create one from a Blob URL if you want everything in one file. Then communicate with postMessage and onmessage.
No. Workers have no access to the DOM or the window object. All DOM updates must be done on the main thread after receiving a message from the worker.
Web Workers are for background computation. Service Workers act as a network proxy and can intercept requests, cache resources, and enable offline functionality.
Call worker.terminate() from the main thread, or use self.close() inside the worker itself.
🧪 Test Your HTML Code
Edit the HTML code on the left and click “Run Code” to see the result on the right.
Click “Run Code” to see the result here.