HTML Web Workers
JavaScript on a web page runs on a single main thread — the same thread that draws the page, handles clicks and runs animations. If your script does a long calculation, everything else waits: buttons stop responding and the page freezes.
A Web Worker is a script that runs on a separate background thread. You hand it heavy work, the page stays smooth, and the worker sends the result back when it is done.
Seeing the problem
Click "Count on main thread" and then immediately try to type in the box. The page freezes until counting finishes.
<!DOCTYPE html>
<html>
<body>
<input placeholder="Try typing here">
<button id="block">Count on main thread</button>
<p id="out"></p>
<script>
document.getElementById('block').onclick = function () {
let total = 0;
for (let i = 0; i < 1e9; i++) { total += i % 3; }
document.getElementById('out').textContent = 'Done: ' + total;
};
</script>
</body>
</html>How workers communicate
A worker cannot touch the page directly — it has no access to document or the DOM. Instead, the page and the worker talk by sending messages:
| Side | Send | Receive |
|---|---|---|
| Page | worker.postMessage(data) |
worker.onmessage = e => e.data |
| Worker | postMessage(data) |
onmessage = e => e.data (or self.onmessage) |
The data is copied, not shared, so neither side can accidentally change the other's variables.
Normally the worker lives in its own file:
// page script
const worker = new Worker('worker.js');
worker.postMessage(1000000);
worker.onmessage = function (e) { console.log('Result:', e.data); };// worker.js
onmessage = function (e) {
let sum = 0;
for (let i = 0; i < e.data; i++) sum += i;
postMessage(sum);
};Inline workers with a Blob
A playground cannot contain a second file, so we use a handy trick: put the worker's code in a string, turn it into a Blob (a file-like object in memory), and give the worker a URL to that blob with URL.createObjectURL. The same technique is useful in real projects for small helper workers.
<!DOCTYPE html>
<html>
<body>
<input placeholder="Type here while it counts">
<button id="go">Count in a worker</button>
<p id="out"></p>
<script>
const code = `
onmessage = function (e) {
let total = 0;
for (let i = 0; i < e.data; i++) { total += i % 3; }
postMessage(total);
};
`;
const out = document.getElementById('out');
let worker = null;
try {
const url = URL.createObjectURL(new Blob([code], { type: 'text/javascript' }));
worker = new Worker(url);
worker.onmessage = function (e) { out.textContent = 'Done: ' + e.data; };
worker.onerror = function (e) { out.textContent = 'Worker error: ' + e.message; };
} catch (e) {
out.textContent = 'Workers are not available here: ' + e.message;
}
document.getElementById('go').onclick = function () {
if (!worker) return;
out.textContent = 'Counting… (the page still responds!)';
worker.postMessage(1e9);
};
</script>
</body>
</html>This time you can keep typing while the worker counts.
Progress updates and stopping a worker
A worker can send as many messages as it likes — useful for progress bars. The page can end a worker at any time with worker.terminate(); inside the worker, close() does the same.
<!DOCTYPE html>
<html>
<body>
<progress id="bar" max="100" value="0"></progress>
<button id="start">Start</button>
<button id="stop">Stop</button>
<p id="msg"></p>
<script>
const src = `
onmessage = function () {
const steps = 100;
for (let s = 1; s <= steps; s++) {
let x = 0;
for (let i = 0; i < 5e6; i++) x += i; // pretend work
postMessage({ progress: s });
}
postMessage({ done: true });
};
`;
const url = URL.createObjectURL(new Blob([src], { type: 'text/javascript' }));
let worker = null;
const bar = document.getElementById('bar');
const msg = document.getElementById('msg');
document.getElementById('start').onclick = function () {
if (worker) worker.terminate();
try { worker = new Worker(url); } catch (e) { msg.textContent = 'Workers unavailable.'; return; }
bar.value = 0;
msg.textContent = 'Working…';
worker.onmessage = function (e) {
if (e.data.done) { msg.textContent = 'Finished!'; worker = null; }
else bar.value = e.data.progress;
};
worker.postMessage('go');
};
document.getElementById('stop').onclick = function () {
if (worker) { worker.terminate(); worker = null; msg.textContent = 'Stopped at ' + bar.value + '%.'; }
};
</script>
</body>
</html>What workers can and cannot use
| Available in a worker | Not available |
|---|---|
postMessage, onmessage |
document, window, the DOM |
setTimeout, setInterval |
alert, confirm |
fetch, XMLHttpRequest |
Direct access to page variables |
importScripts(), IndexedDB |
localStorage |
Other kinds of workers
- Shared workers can be used by several tabs of the same site at once.
- Service workers sit between the page and the network; they power offline sites and push notifications.
Tip: Workers have a start-up cost. Use them for genuinely heavy jobs — image processing, parsing big files, complex maths — not for tiny tasks that finish in a millisecond.
Test yourself
Why use a Web Worker?
- To style the page
- To run heavy JavaScript on a background thread so the page stays responsive
- To store data permanently
- To load images faster
How does a worker send a result back to the page?
document.write()return resultpostMessage(result)console.log(result)
Which of these can a worker NOT access?
setTimeoutfetchdocumentpostMessage