Don't let the main thread carry it all: Web Workers, handing heavy work to another thread
The main thread has to draw the page and do the accounts, so it freezes the moment the work gets heavy. A worker is another thread in another global context, and the two sides talk only through messages. Following MDN's Using Web Workers and Worker docs: new Worker, postMessage and onmessage, structured-clone copying, what a worker can and cannot do, onerror and terminate(), SharedWorker, and transferable zero-copy — with a 100-mistake breakdown from a fictional cafe order page.

First, the boundaries of this guide. The site already has several JavaScript basics guides: the event loop guide explains how tasks queue up on a single thread, the Promise and async guide explains how to wait for an asynchronous result, and the generators guide explains handing out one value at a time, only when asked. This guide covers none of those. It covers just one thing: when the main thread cannot keep up, how to hand heavy work to another thread — Web Workers. The "Qingshi Cafe" below is the same fictional practice project used in earlier guides: a small web tool that takes orders for a street-side cafe. Earlier guides covered how its order page makes decisions, loops, takes numbers, and schedules time; this one covers its end-of-month reconciliation: the owner has to check a 2,000-row statement and work out the best combination of discounts — spend-over-X, second-cup-half-price, member pricing. The moment the main thread starts on it, the page freezes: buttons stop responding, the pickup numbers stop refreshing, and everything jumps at once when the calculation finally finishes. Every operation, code sample, and number built around it is invented to explain the technique, not a real record. All syntax and behavior of workers comes from MDN's official docs, "Using Web Workers" and "Worker"; sources are listed in each article's meta information and evidence record. After reading this guide, you should be able to do four things: create a worker, send messages back and forth with postMessage and onmessage, know what a worker can and cannot do, and know when to use a worker and when not to. The event loop guide explained "how tasks queue up on one thread"; this guide explains "how to open a second thread". Together they give the full picture of concurrency in the browser.
Step 1: The problem — the main thread has to draw the page and do the accounts
The Qingshi Cafe order page usually runs smoothly, until the owner opens "End-of-month reconciliation": 2,000 rows of orders to check one by one, plus working out which combination of discounts — spend-over-X, second-cup-half-price, member pricing — saves the most. There is only one main thread, and it has to draw the page, answer button clicks, and run the reconciliation code at the same time. Once the calculation starts, the page freezes: buttons do nothing when clicked, pickup numbers stop refreshing, and everything jumps forward at once when the calculation finally ends. The problem is not a bug in the code; it is that the work is too heavy. On a single thread, the calculation and the page drawing compete for the same time. The worker approach moves the work to another thread: the calculation, code and all, goes to a second thread, and the main thread is left with two jobs — receiving the result and drawing it on the page. MDN's words: workers are mainly useful for allowing your code to perform processor-intensive calculations without blocking the user interface thread — in the MDN example, a worker is used to calculate Fibonacci numbers. Remember this split for now: the main thread owns the page, the worker owns the heavy work, and the two sides talk only through messages.
Step 2: What a worker is — another thread, another global context
MDN's definition of a worker is a single sentence: the Worker interface represents a background task that can be created via script, which can send messages back to its creator. Creating a worker is simple — call the constructor with the address of a script: const myWorker = new Worker("worker.js"). But three things sit behind that one line, and they are worth understanding first. First, the worker runs in another global context, called a DedicatedWorkerGlobalScope, a different place from the current page's window. MDN's words: workers run in another global context that is different from the current window. Thus, using the window shortcut to get the current global scope (instead of self) within a Worker will return an error. Second, a dedicated worker belongs only to the script that created it. MDN's words: a dedicated worker is only accessible from the script that first spawned it, whereas shared workers can be accessed from multiple scripts. Shared workers get their own step, step 9. Third, workers can spawn more workers, as long as those workers are hosted within the same origin as the parent page, and the addresses of sub-workers are resolved relative to the parent worker's location rather than the owning page. My judgment: think of a worker as a new helper hired into the shop — their own table, their own tools. The main thread is the front counter; the helper does the accounts in the back kitchen. Front and back pass notes to each other, and neither reaches over to move things on the other's table.
Step 3: Creating a worker — ask the browser first whether it supports one
Before creating a worker, ask whether the browser supports them. MDN recommends wrapping the worker code like this:
if (window.Worker) {
// …
}
If the browser supports workers, carry on; if not, fall back to the old way instead of letting the page throw an error. MDN's basic example multiplies two numbers: the main thread has two input boxes, and whenever either value changes it sends a message to the worker; the worker multiplies them and sends the result back, and the page displays it. There are two ways to write the constructor call. The first gives an address relative to the page: const myWorker = new Worker("worker.js"). The second is the form bundlers recommend: const myWorker = new Worker(new URL("worker.js", import.meta.url)), which makes the path relative to the current script instead of the current HTML page, so the bundler can safely rename files and optimize. MDN's words: this way, the path is relative to the current script instead of the current HTML page, which allows the bundler to safely do optimizations like renaming — because otherwise the worker.js URL may point to a file not controlled by the bundler, so it cannot make any assumptions. The cafe example: the reconciliation worker is called reconcile.js; the main thread creates it and sends it 2,000 rows of orders, and everything else happens in the back kitchen. One more detail: the Worker constructor also accepts Blob URLs — code can be assembled into a Blob, turned into an object URL, and passed in. MDN does exactly that in its "embedded worker" section, which step 10 mentions again.
Step 4: postMessage and onmessage — the two sides talk only through messages
All the magic of workers lives in two things: the postMessage method and the onmessage event handler. When the main thread wants to send a message to the worker, it calls postMessage on the worker object; when the worker wants to send a message back, it calls postMessage too. Both sides receive messages through onmessage, and the message itself sits in the message event's data attribute. MDN's multiplication example, on the main thread:
[first, second].forEach((input) => {
input.onchange = () => {
myWorker.postMessage([first.value, second.value]);
console.log("Message posted to worker");
};
});
Inside the worker:
onmessage = (e) => {
console.log("Message received from main script");
const workerResult = `Result: ${e.data[0] * e.data[1]}`;
console.log("Posting message back to main script");
postMessage(workerResult);
};
And back on the main thread, receiving the answer:
myWorker.onmessage = (e) => {
result.textContent = e.data;
console.log("Message received from worker");
};
When either input box changes, the main thread packs both values into an array and sends it; the worker multiplies them and sends the result back; the main thread writes the result into the page. MDN flags one asymmetry worth remembering: notice that onmessage and postMessage() need to be hung off the Worker object when used in the main script thread, but not when used in the worker. This is because, inside the worker, the worker is effectively the global scope. My judgment: think of postMessage as "passing a note" and onmessage as "what to do when a note arrives". A note can carry almost anything — an array, an object, a number — but notes travel one at a time, one way at a time; two people cannot reach in and edit the same note together.
Step 5: Messages are copied across, not shared
Data passed between the main page and a worker is copied, not shared. MDN's words: data passed between the main page and workers is copied, not shared (except for certain objects that can be explicitly shared). Objects are serialized as they're handed to the worker, and subsequently, de-serialized on the other end. The page and worker do not share the same instance, so the end result is that a duplicate is created on each end. Most browsers implement this feature as structured cloning. MDN's example sends an object carrying a date from the main thread:
const myWorker = new Worker("my_task.js");
myWorker.onmessage = (event) => {
console.log(`Worker said : "${event.data}"`);
};
myWorker.postMessage({ lastUpdate: new Date() });
Inside the worker:
self.onmessage = (event) => {
postMessage(`Last updated: ${event.data.lastUpdate.toDateString()}`);
};
What arrives is still a Date object that can call toDateString() — it did not turn into a string on the way. MDN also writes that the structured cloning algorithm can accept JSON and a few things that JSON can't — like circular references. The direct consequence of copying is that when the main thread changes its own copy, the worker's copy does not change with it, and the other way around. My judgment: think of postMessage as "photocopying a page and mailing it over". The original stays in your hand, the copy arrives in theirs, and each side edits their own copy without affecting the other. The cafe example: the main thread sends 2,000 rows of orders to the worker; the worker works out discount combinations on its copy, while the order list on the main thread is untouched. When the worker finishes, it mails the result back, and the main thread draws the page from it.
Step 6: Inside a worker you cannot touch the DOM — but you can fetch, and you can use IndexedDB
The first thing a worker cannot do is directly manipulate the DOM, or use some default methods and properties of the window object. MDN's words: you can run whatever code you like inside the worker thread, with some exceptions. For example, you can't directly manipulate the DOM from inside a worker, or use some default methods and properties of the window object. But plenty remains available. MDN lists WebSockets and data storage mechanisms like IndexedDB, and workers can make network requests using the fetch() or XMLHttpRequest APIs — although note that the responseXML attribute of XMLHttpRequest will always be null. Near the end of the article MDN gives another list: you can use most standard JavaScript features inside a web worker, including Navigator, fetch(), Array, Date, Math, and String, and setTimeout() and setInterval(). What you cannot do, MDN puts plainly: the main thing you can't do in a Worker is directly affect the parent page. This includes manipulating the DOM and using that page's objects. You have to do it indirectly, by sending a message back to the main script via postMessage(), then doing the changes in the event handler. The cafe example: when the reconciliation worker finishes, it cannot change the numbers on the pickup board itself; it has to send "which rows don't match, which discount combination won" back to the main thread, and the main thread updates the page. My judgment: to decide whether something works inside a worker, do not memorize a list — ask one question, "does it need to touch the page?" If it does, send a message back to the main thread; if it does not, use it freely.
Step 7: When something goes wrong — onerror and terminate()
Code running in a worker can fail too, and the main thread needs to know. The way to find out is to attach an onerror handler to the worker, exactly as MDN's Fibonacci example does:
worker.onerror = (error) => {
console.log(`Worker error: ${error.message}`);
throw error;
};
MDN's words: when a runtime error occurs in the worker, its onerror event handler is called. It receives an event named error which implements the ErrorEvent interface. The event doesn't bubble and is cancelable; to prevent the default action from taking place, the worker can call the error event's preventDefault() method. The error event has three fields worth knowing: message, a human-readable error message; filename, the name of the script file in which the error occurred; and lineno, the line number of the script file on which the error occurred. The other half of this step is ending a worker. To immediately terminate a running worker from the main thread, call the worker's terminate() method — myWorker.terminate() — and the worker thread is killed immediately. The Worker reference page says it even more bluntly: terminate() immediately terminates the worker. This does not let the worker finish its operations; it is halted at once. My judgment: terminate() means "stop now", not "finish up first". Use it to clear the reconciliation worker at closing time. But if the worker is in the middle of writing to IndexedDB or sending a request, killing it at once can leave things half done; if it should send a "finished writing" message first, wait for that message instead of cutting corners.
Step 8: Sub-workers and importScripts — a worker can split its work further
Workers may spawn more workers if they wish. Worker threads also have a global function, importScripts(), which lets them import scripts — it accepts zero or more URIs, and the browser loads each listed script and executes it. The rules of importScripts are worth remembering. First, scripts may be downloaded in any order, but they are executed in the order in which you pass the filenames into importScripts(). Second, this is done synchronously; importScripts() does not return until all the scripts have been loaded and executed. Third, if a script can't be loaded, NETWORK_ERROR is thrown, and subsequent code will not be executed — but previously executed code, including code deferred using setTimeout(), will still be functional. Fourth, function declarations after the importScripts() method are also kept, since these are always evaluated before the rest of the code. The rule for sub-workers is that they must be hosted within the same origin as the parent page, and the URIs for sub-workers are resolved relative to the parent worker's location rather than that of the owning page, which makes it easier for workers to keep track of where their dependencies are. The cafe example: the reconciliation worker splits into two sub-workers, one for spend-over-X discounts and one for member pricing; each sends its result back to the reconciliation worker, which totals them up and sends the answer to the main thread. My judgment: beginners should not worry about sub-workers yet — get one worker running smoothly first. Only when one worker itself cannot keep up should you split it, following MDN's rules, and when you do, remember "same origin" and "addresses relative to the parent worker".
Step 9: SharedWorker — one worker serving several pages
A dedicated worker belongs only to the script that created it. A shared worker is different: it is accessible by multiple scripts — even if they are being accessed by different windows, iframes or even workers. MDN's words: a shared worker is accessible by multiple scripts — even if they are being accessed by different windows, iframes or even workers. Creating one is almost the same as a dedicated worker, with a different constructor name: const myWorker = new SharedWorker("worker.js"). The big difference is communication: with a shared worker you have to communicate via a port object — an explicit port is opened that the scripts can use to communicate with the worker (this is done implicitly in the case of dedicated workers). MDN's example has two pages sharing one worker — one page multiplies numbers, the other squares them — and the worker looks like this:
onconnect = (e) => {
const port = e.ports[0];
port.onmessage = (e) => {
const workerResult = `Result: ${e.data[0] * e.data[1]}`;
port.postMessage(workerResult);
};
};
When a connection arrives, onconnect fires; the port is taken from the event's ports attribute, and onmessage is attached to that port. The main thread sends through the port — myWorker.port.postMessage([squareNumber.value, squareNumber.value]) — and receives through it as well: myWorker.port.onmessage = (e) => { result2.textContent = e.data; }. The port connection needs to be started before any messages can be posted: setting an onmessage handler opens it implicitly, while wiring the message event up via addEventListener requires an explicit start() call — and when using start(), it needs to be called from both the parent thread and the worker thread if two-way communication is needed. When does a shared worker shut down? MDN's words: shared workers are shut down when they are no longer referenced by any windows, iframes, or workers. Browsers may keep workers alive between same-origin navigations to avoid the cost of restarting a shared worker used by a site when the user is navigating from page to page within that site. The extendedLifetime constructor option may also be specified to keep a shared worker alive for a short period after all references to it have closed — new SharedWorker("worker.js", { extendedLifetime: true }) — which allows work to be done after the user navigates away, such as writing state information to storage, or sending analytics data back to servers. My judgment: a shared worker is "one back kitchen shared by several counters". Use it when the order page and the pickup board share one calculation worker; for a single page on its own, a dedicated worker is enough. Do not reach for it just to use it.
Step 10: Moving large data — transferable objects move with zero copy, and the original is emptied
Copying has a cost: the bigger the data, the slower the photocopy. MDN describes another way: transferable objects are transferred from one context to another with a zero-copy operation, which results in a vast performance improvement when sending large data sets. MDN's example moves a 32MB array:
// Create a 32MB "file" and fill it with consecutive values from 0 to 255 – 32MB = 1024 * 1024 * 32
const uInt8Array = new Uint8Array(1024 * 1024 * 32).map((v, i) => i);
worker.postMessage(uInt8Array.buffer, [uInt8Array.buffer]);
The second argument to postMessage is the transfer list: objects listed there are moved, not copied. MDN's words: when transferring an ArrayBuffer from your main app to a worker script, the original ArrayBuffer is cleared and no longer usable. Its content is (quite literally) transferred to the worker context. In other words, after the transfer the buffer on the main thread is empty — reading it again will fail, and to use it again the worker has to send it back. MDN also mentions SharedArrayBuffer: it allows two threads, such as the worker and the main thread, to simultaneously operate on the same memory span and exchange data without going through the messaging mechanism — but using shared memory does come with significant determinism, security, and performance concerns, some of which are outlined in the JavaScript execution model article. MDN does not go further than that here. My judgment: use copying by default, and only switch to transferring when the data is genuinely large enough for copying to hurt; when you transfer, remember "it is emptied once sent" and do not keep a reference to that buffer on the main thread. The cafe example: 2,000 rows of orders are only a few dozen kilobytes, so copying them is fine. If one day a whole year's statements — tens of megabytes — need to cross over, that is when to switch to transfer.
Step 11: When to use a worker, when not to, and a checklist
Finally, the selection guide. Workers fit three kinds of work. First, heavy calculation: Fibonacci numbers, discount combinations, reconciliation statements — work that would freeze the main thread. Second, parsing large files or processing images — "big data, long calculation" work. Third, work that runs in the background for a long time without touching the page. MDN's words: as multicore computers become increasingly common, it's often useful to divide computationally complex tasks among multiple workers, which may then perform those tasks on multiple-processor cores. The cases that do not fit are worth remembering too: when the job itself is tiny, the cost of starting a worker and passing messages back and forth outweighs the job — do not use a worker just to use one. And jobs that have to change the DOM directly cannot run in a worker at all; they still have to send a message back to the main thread, which adds a round trip. Two relatives are easy to mistake for workers: Service Workers essentially act as proxy servers that sit between web applications, and the browser and network — they enable offline experiences, intercepting network requests, and access to push notifications and background sync APIs. They are not for calculations. Audio Worklets provide the ability for direct scripted audio processing in a worklet, a lightweight version of a worker — also not for calculations. Debugging a worker is nothing to fear. MDN's words: most browsers enable you to debug web workers in their JavaScript debuggers in exactly the same way as debugging the main thread. For example, both Firefox and Chrome list JavaScript source files for both the main thread and active worker threads, and all of these files can be opened to set breakpoints and logpoints. Chrome opens them at chrome://inspect, Firefox at about:debugging. Run through this checklist: is the worker script address correct, and same-origin; did you check if (window.Worker); messages are copied across — did you remember that changing your own copy does not change the worker's copy; does the worker touch the DOM directly, or use window; is onerror attached for errors; did you call terminate() when the worker is no longer needed; for a SharedWorker, is the port opened, and did you call start() where it is required?
The chart above shows the causes of 100 worker mistakes in one month on the fictional Qingshi Cafe order page: operating the DOM directly inside a worker, as if it were the main thread — 26; changing the object on the main thread and expecting the worker's copy to change too — 18; reading the result immediately after sending the message, forgetting the worker answers asynchronously — 15; a wrong worker script address or a cross-origin address, the file returning 404 with no onerror attached — 13; never calling terminate(), leaving the worker holding its thread — 11; passing a function to postMessage and expecting functions to travel across — 9; believing the worker and the main thread share the same memory and the same variables — 8. 26 + 18 + 15 + 13 + 11 + 9 + 8 = 100; the books balance. The top three mistakes add up to almost sixty percent, and they are all the same misunderstanding: treating the worker as part of the main thread. A worker is another thread in another global context; messages are photocopied across, and results come back asynchronously. Every category in the chart maps to a step in this guide: the first to step 6, the second to step 5, the third to step 4, the fourth to steps 3 and 7, the fifth to step 7, the sixth to step 5, the seventh to steps 5 and 10. The next time a worker misbehaves, check in this order: does the worker touch the DOM or use window, are messages copied across, and do results come back asynchronously. Two steps will usually find it.
Back to the four things from the start: new Worker("worker.js") creates a background task running in a DedicatedWorkerGlobalScope, with no window — use self; postMessage sends a message and onmessage receives one, and messages are copied across rather than shared; inside a worker you cannot touch the DOM, but you can use fetch, IndexedDB, and setTimeout, and page changes have to be sent back to the main thread as messages; heavy calculation, large files, and long background jobs fit workers, while tiny jobs and jobs that change the DOM directly do not. The event loop guide explained "how tasks queue up on one thread"; this guide explained "how to open a second thread". Together they cover time and concurrency in the browser. After this guide, move the order page's end-of-month reconciliation into a worker: the main thread only receives results and draws the page, the accounts are done in the back kitchen, and the buttons will stop freezing.
Comments (0)
Sources
Related articles
setTimeout handles once, setInterval handles repeatedly — but delay only promises "at least this long": 0 is not immediate, background tabs run even later, and anything over 2147483647 overflows. Following MDN's setTimeout and setInterval docs: async return, argument passing, the delay rules, the 4 ms nesting clamp, clearTimeout and clearInterval, recursive setTimeout, lost this, and string arguments — with a 100-mistake breakdown from a fictional cafe order page.
An array has to be computed all at once; a generator hands out one value at a time, only when asked. Following MDN's Iterators and generators, function*, and Generator docs: the next() protocol, function* and yield, for...of consumption, Symbol.iterator, yield* delegation, sending values in with next(x), throw() and return(), and when to use a generator at all — with a 100-mistake breakdown from a fictional cafe order page.
One missing layer in your data can blank the whole order page. Following MDN's Optional chaining, Nullish coalescing, and Logical nullish assignment docs: the three forms of ?., short-circuiting, optional calls and bracket access, ?? vs || on 0 and empty strings, the ?. + ?? combination, the ban on mixing ?? with || and &&, and ??= defaults — with a 100-mistake breakdown from a fictional cafe order page.