The sales report on your phone is working out the statistics of 100,000 transactions. For those 1.5 seconds the Like button won't respond, scrolling freezes, and the page looks hung.
A Web Worker is a second JavaScript thread that runs beside the main thread. Heavy work moves there, so the main thread stays free to respond to clicks and draw the screen. Picture a restaurant kitchen whose cook also serves the guests out front. An order comes in for 50 kg of onions to chop, so the cook asks an assistant in the back kitchen for help. That assistant is the worker: they cannot come out to the dining room, they only receive orders on a slip of paper and send the result back on a slip of paper too.
Main thread versus worker
From the previous lesson: there is only one main thread, and while it runs a task, clicks have to wait in line. A worker has its own thread, so work there does not hold up the main thread.
Simulated numbers from the Lab on this page: the statistics take 1,500 ms, then showing the result takes 10 ms. You click the Like button at the 500 ms mark.
| Worked out on the main thread | Worked out in a Web Worker | |
|---|---|---|
| Main thread busy | 1,510 ms without a break | 40 ms to send the data, then 10 ms to show the result |
| Like clicked at 500 ms | waits 1,010 ms | handled at once |
| Result shown | at 1,510 ms | at 1,591 ms |
In the worker, the result still takes about 1,500 ms, even a little longer because the data has to travel there and back. A worker does not make JavaScript faster. The gain: during those 1,500 ms the page stays responsive, so Like goes up at once.
Making a worker
A worker's code lives in a separate file. The main thread and the worker talk through messages.
// main.js
const worker = new Worker("statistics.js");
calculateButton.addEventListener("click", () => {
worker.postMessage(transactions); // send 100,000 transactions
});
worker.onmessage = (event) => {
showResult(event.data); // the result from the worker
};
// statistics.js (runs in the worker)
self.onmessage = (event) => {
const transactions = event.data;
const total = transactions.reduce((sum, t) => sum + t.amount, 0);
self.postMessage({ total, average: total / transactions.length });
};
new Worker("statistics.js")runs that file on a new thread.worker.postMessage(data)sends data to the worker. Inside the worker, it arrives asevent.datainself.onmessage.selfis the global object inside a worker, in place ofwindow.self.postMessage(result)sends the result back, and the main thread receives it inworker.onmessage.- Once the worker is no longer needed, stop it with
worker.terminate(). - In a project with a bundler such as Vite, write
new Worker(new URL("./statistics.js", import.meta.url), { type: "module" })so the worker file is bundled too.
What a worker cannot do
A worker has no access to the DOM: inside it there is no document and no window. Writing document.querySelector("#result") in a worker fails at once: ReferenceError: document is not defined. So the worker only computes and sends its result. Changing what is on screen stays with the main thread, in worker.onmessage.
What still works: fetch, setTimeout, IndexedDB, WebSocket and any ordinary computation. It suits parsing big data (JSON, CSV), processing images, encryption or hashing, and sorting large amounts of data.
Data is copied or moved
postMessage copies the data using what is called the structured clone. Objects, arrays, Map, Date and ArrayBuffer can be sent. Functions and DOM elements cannot: postMessage throws a DataCloneError right away. Because it is a copy, changing the original object after sending it does not change the worker's copy. Copying has a cost too: in the Lab, 100,000 objects take 40 ms on the main thread.
Binary data in an ArrayBuffer can be moved (transferred) instead of copied. It is almost free, but afterwards the sender no longer has the data.
const amounts = new Float64Array(100000); // 800 KB of numbers
worker.postMessage(amounts.buffer, [amounts.buffer]);
console.log(amounts.buffer.byteLength); // 0, it now belongs to the worker
- The second argument,
[amounts.buffer], is the list of what to move. Without it, the buffer is copied. - After the move,
byteLengthon the main thread becomes0. The worker owns it now.
There is also SharedArrayBuffer for memory both threads use at once, but it needs cross-origin isolation headers on the server and is rarely needed.
⚠️ When a worker causes more trouble than it saves
- Moving small work. Sending data has a cost. Filtering 50 items is faster right on the main thread.
- Changing the DOM from a worker. There is no
documentin a worker. Send the result, then change the DOM inworker.onmessage. - Sending a function or a DOM element. Neither can be cloned, so you get a
DataCloneError. Send only the data. - Forgetting
terminate(). A worker nobody uses any more stays alive and keeps using memory.
TL;DR: A Web Worker runs JavaScript on a separate thread, so heavy work does not hold up the main thread and the page stays responsive. The work does not get faster (1,500 ms is still about 1,500 ms), but clicks no longer wait in line. Make one with new Worker("file.js"), send with postMessage, receive in onmessage, and stop it with terminate(). A worker cannot reach the DOM (there is no document or window), so it sends its result and the main thread changes the screen. Data is copied by the structured clone (functions and DOM elements cannot be), and an ArrayBuffer can be moved through the transfer list, which leaves its byteLength at 0 on the sender.
⚡ A second thread for heavy work
Guess first: 1,500 ms of statistics move to a Web Worker. Does the result come out faster?
No. The result still takes about 1,500 ms, even a little longer because the data has to travel there and back. The gain: the heavy JavaScript runs on another thread, so the main thread stays responsive and Like goes up at once.
Meaning: A Web Worker is a second JavaScript thread beside the main thread. A worker doesn't make JavaScript faster, it keeps clicks from waiting in line.
⚡ Talking through messages
Write:
const worker = new Worker("statistics.js");
worker.postMessage(transactions);
worker.onmessage = (event) => {
showResult(event.data);
};
Meaning: postMessage sends data, and on the other side it arrives as event.data. Inside the worker, self.postMessage sends the result back. Stop a worker you no longer need with terminate().
⚡ No DOM in a worker
Meaning: Inside a worker there is no document and no window, so the worker only computes, and the main thread changes the screen. Data is copied by the structured clone: functions and DOM elements can't be sent.