Web Workers Explained: Moving Heavy JavaScript Off the Main Thread
Saket Bhatnagar, Founder, SevyDevy, Last updated , 19 min read
Summary
- Web workers explained in one line: a web worker runs JavaScript on a second thread, a separate line of work, so slow jobs stop freezing clicks and typing.
- The main thread is the one thread that runs your page's JavaScript and handles input. A task that holds it for 50 milliseconds or more is called a long task.
- A worker cannot touch the page. It talks to the page by sending messages with postMessage, which copies the data, much like sending a photocopy instead of the original.
- Big binary data can be transferred instead of copied. Ownership moves to the other thread, and the sender's copy becomes empty, with zero bytes.
- Beginners can stop after the parsing example. Engineers get our measured runs after it: a worker that sends 2 lakh parsed rows back froze the page longer than parsing on the main thread did.
What goes wrong when heavy JavaScript runs on the main thread?
The page freezes until the work is done. Web workers explained simply: they give that work its own thread, so the page keeps answering the user. Before the fix, it helps to see the freeze clearly.
Browsers run your page's JavaScript on one main thread. That same thread runs your click and key handlers and the code that updates the screen. While one piece of JavaScript is running, every handler waits in line.
Picture a common setup. An admin dashboard downloads a 12.8 MB JSON export of 2 lakh (200,000) orders, parses it and filters the paid ones. The setup is made up, but the freeze is real and we measured it.
We ran exactly that in headless Chromium 153 on a 2-core Linux machine. On three fresh page loads, the fetch, the res.json() call and the filter produced one long task of 177 to 196 milliseconds. A promise-based API did not save the main thread.
Then we blocked the main thread with a 500 millisecond loop. A timer set for 0 milliseconds fired after 500.2 milliseconds. Over 550 milliseconds, a timer meant to tick every 10 milliseconds ticked 6 times instead of about 55.
Which words do you need before reading about web workers?
Six terms carry the whole guide. Each gets a plain meaning here and keeps that meaning throughout.
- Thread: one line of work a processor runs. Two threads can run at the same time on two cores.
- Main thread: the browser thread that runs your page's JavaScript, handles input and updates the page.
- Task: one chunk of work the main thread runs from start to finish, such as one click handler or one timer callback.
- Long task: a task that keeps the main thread busy for 50 milliseconds or more, as defined in the Long Tasks API on MDN.
- INP (Interaction to Next Paint): a score for how fast the page reacts to taps, clicks and keys. It is one of the Core Web Vitals, the page-experience measures web.dev tracks.
- Message: a value one thread sends to another with postMessage. The receiver gets it in a message event.
INP counts as good at 200 milliseconds or less and poor above 500 milliseconds, measured at the 75th percentile of visits, according to web.dev as of 31 October 2026. A tap that lands during one 196 millisecond task can wait almost that long. That alone nearly uses up the 200 millisecond budget.
What are web workers, explained in plain words?
A web worker is a script the browser runs on a separate thread, next to your page. MDN notes that each worker is a real operating-system thread.
You start one with new Worker and the script's URL. The page and the worker then send each other messages. Neither can reach into the other's variables.
Think of a busy restaurant counter. The main thread is the one person at the counter who takes orders and hands food over. A worker is a cook in the back kitchen.
- The counter person is the main thread: the only one who faces customers, the way only the main thread can touch the page.
- The cook is the worker: they can do long jobs without making the queue wait.
- Order slips through the hatch are messages: the cook works from a photocopy of the slip, not the original.
- Hiring a cook costs money and space: each worker costs start-up time and memory.
Where the picture breaks: a real cook can walk into the dining room, but a worker never can. And for binary data you can hand over the original instead of a copy, which the transfer section covers.
How the page and a worker talk
Drag to exploreNotice that every arrow passes through a message. The worker never touches the page, and the main thread never waits for the worker unless your code makes it wait.
Diagram connections:
- User clicks and types to Main thread (click)
- Main thread to postMessage to worker (send job)
- postMessage to worker to Worker thread (message event)
- Worker thread to postMessage to page (send result)
- postMessage to page to Main thread (message event)
- Main thread to Updated table (update the page)
- User clicks and types: Input arrives on the main thread
- Main thread: Runs handlers, owns the page
- postMessage to worker: Main → Worker: a copy of the data
- Worker thread: Parses and filters, no page access
- postMessage to page: Worker → Main: a small result
- Updated table: Main thread renders 50 rows
| Feature | Inside a worker? | What it means for you |
|---|---|---|
| document and the DOM (the page's elements) | No, typeof document is undefined | Send results back and let the main thread update the page |
| window | No, typeof window is undefined | Use self to refer to the worker's own global scope |
| localStorage | No, typeof localStorage is undefined | Use IndexedDB, or send values in a message |
| fetch | Yes | The worker can download data itself |
| IndexedDB (the browser's built-in database) | Yes | The worker can read and save large data |
| OffscreenCanvas (a canvas you can draw on without the page) | Yes | Drawing can move off the main thread |
| SharedArrayBuffer (memory both threads can see) | Only when the page is cross-origin isolated | See the shared memory section near the end |
How do you move JSON parsing into a web worker?
Put the fetch, the parse and the filter inside the worker, and send back only what the screen needs. The 12.8 MB text then never touches the main thread.
Write the worker file
Create orders-worker.js. It listens for a message, fetches the URL it was given, parses it and keeps the paid orders.
Send back only what the screen needs
Reply with the counts and the first 50 rows. The table shows 50 rows per page, so the rest can stay in the worker.
Start the worker from the page
In main.js, call new Worker with the file name. The file must come from the same origin as the page, meaning the same scheme, host and port. A blob or data URL, built in code, also works.
Listen for results and errors
Set onmessage for results and onerror for crashes. Then post a message that tells the worker which URL to load.
// orders-worker.js: runs on its own thread, never touches the page
self.onmessage = function (event) {
fetch(event.data.url)
.then(function (res) { return res.json(); })
.then(function (rows) {
var paid = rows.filter(function (row) { return row.status === 'paid'; });
self.postMessage({ total: rows.length, paid: paid.length, firstPage: paid.slice(0, 50) });
});
};// main.js: runs on the main thread, owns the page
var worker = new Worker('orders-worker.js');
worker.onmessage = function (event) {
console.log('rows:', event.data.total, 'paid:', event.data.paid, 'shown:', event.data.firstPage.length);
};
worker.onerror = function (event) {
console.error('worker failed:', event.message);
};
worker.postMessage({ url: 'orders.json' });Load main.js from a page served over HTTP, then open the browser console. With our test file you should see one line: rows: 200000 paid: 133333 shown: 50.
What just happened? The worker downloaded and parsed 2 lakh rows on its own thread. Our long task observer, shown later, logged no long task from this work. The same job on the main thread had logged 177 to 196 milliseconds.
If the worker throws, the page's onerror handler gets an event with message, filename and lineno fields. In our test it read Uncaught Error: boom inside worker, line 1.
Classic workers and module workers
A plain new Worker call makes a classic worker. Pass the option type set to module to allow import statements inside the worker file.
Forget the option and the import fails. Chromium reported SyntaxError: Cannot use import statement outside a module.
When the page no longer needs the worker, call worker.terminate(). MDN says the thread is killed immediately. In our test, a message posted after terminate got no reply.
What does postMessage really cost?
Every message is copied unless you transfer it or use shared memory, and copying takes time on both threads. The browser uses the structured clone algorithm. MDN describes it as serialising the value, turning it into bytes, on one side and building a duplicate on the other.
Structured clone handles more than JSON. In our test, Map, Set, Date, RegExp, a TypeError, a BigInt and an object that points to itself all arrived intact.
Some values do not survive. Functions and DOM elements throw a DataCloneError, so the message is never sent. A class instance arrives as a plain object: its data fields stay, but its methods and getters are gone.
Size matters most. We posted an 8 MB and a 64 MB ArrayBuffer, a block of raw bytes, to a worker that summed it. Each figure below is the median of seven runs.
| Data | Main thread time inside postMessage | Round trip to the worker and back | Sender's buffer afterwards |
|---|---|---|---|
| 8 MB, copied | 9.1 ms | 14.9 ms | Still 8 MB, still usable |
| 8 MB, transferred | 0.1 ms | 4.5 ms | 0 bytes, no longer usable |
| 64 MB, copied | 49.9 ms | 108.5 ms | Still 64 MB, still usable |
| 64 MB, transferred | 0.5 ms | 24.3 ms | 0 bytes, no longer usable |
At 64 MB, the copy alone held the main thread for about 50 milliseconds. That sits right at the long-task line, caused by the very call meant to avoid one.
Transferring moves the buffer instead of copying it
A transfer hands the memory itself to the other thread. You list the buffer in the second argument of postMessage. Below, pixels is a typed array: a list of numbers stored in one ArrayBuffer. Here worker stands for any worker you have created. MDN calls ArrayBuffer transfer a zero-copy operation.
var pixels = new Uint8ClampedArray(4 * 1920 * 1080);
console.log('before:', pixels.byteLength);
worker.postMessage({ pixels: pixels }, [pixels.buffer]);
console.log('after:', pixels.byteLength);Run it and the console shows before: 8294400, then after: 0. The typed array on the main thread now has no bytes, because the worker owns them.
Two rules come from the HTML Standard and showed up in our run. Posting a buffer that was already transferred throws a DataCloneError. Listing the same buffer twice in one transfer list also throws.
Typed arrays such as Uint8Array are not transferable themselves; their underlying buffer is. Other transferable types include ImageBitmap, OffscreenCanvas, MessagePort and the stream types, per MDN's list.
When do web workers make a page slower?
A worker backfires when the data going in or coming out costs more than the work you moved. The browser still has to rebuild every received object on the main thread.
No, it was busy for longer. We ran three designs on the same 12.8 MB text in three browser sessions, five tries each. Here the text was already downloaded and the page warmed up, so main-thread parsing with JSON.parse was much faster than the cold res.json() run at the top.
| Design | Main-thread cost | What the user feels |
|---|---|---|
| Parse and filter on the main thread | 41 to 58 ms to parse, about 5 ms to filter | A short freeze, right at the long-task line |
| Worker parses, posts all 2 lakh rows back | One long task of 77 to 88 ms | A longer freeze than not using a worker |
| Worker parses, posts 50 rows back | No long task | The page stays responsive |
The middle design added work instead of removing it. The worker still parsed, and the main thread then rebuilt 2 lakh objects from the message.
In Chromium, the rebuild cost appeared when our code first read event.data, which took 78 to 88 milliseconds. This timing is undocumented as of 31 October 2026; pin your browser version when you measure.
Sending a big object graph into a worker hurts too. Posting the 2 lakh parsed objects took 60 to 68 milliseconds inside the postMessage call, all on the main thread.
Should this job move to a worker?
Drag to exploreNotice that the size of the reply decides as much as the size of the job. A worker that answers with everything moves the freeze, it does not remove it.
Diagram connections:
- A slow job on the page to Over 50 ms on real devices? (measure)
- Over 50 ms on real devices? to Keep it on main thread (No)
- Over 50 ms on real devices? to Needs the DOM? (Yes)
- Needs the DOM? to Small or binary reply? (No)
- Needs the DOM? to Keep it on main thread (Yes)
- Small or binary reply? to Move it to a worker (Yes)
- Small or binary reply? to Shrink the reply first (No)
- Shrink the reply first to Move it to a worker (then)
- A slow job on the page: Parsing, sorting, searching, image maths
- Over 50 ms on real devices?: Measure on a mid-range phone first
- Needs the DOM?: Reading or changing page elements
- Small or binary reply?: A summary, one page of rows, a buffer
- Keep it on main thread: Split it into smaller tasks if needed
- Shrink the reply first: Send counts, pages or a transferred buffer
- Move it to a worker: One long-lived worker, small messages
Four other ways a worker backfires
- Tiny jobs: a message round trip averaged about 0.02 ms in our runs, while summing 1,000 numbers took 0.003 to 0.012 ms. The postage cost more than the work.
- A new worker per job: starting one and getting its first reply took a median of 9.5 to 17 ms in our runs, with a cached script on localhost.
- Too many workers: the HTML Standard says workers are heavy-weight, with a high start-up cost and a high memory cost per instance. They are not meant to be used in large numbers.
- DOM-heavy work: reading or changing page elements, and the layout work that follows, cannot move to a worker. A worker can only compute what the page should show.
For a pool of workers, navigator.hardwareConcurrency gives the number of logical processors. MDN warns the browser may report fewer, so treat it as an upper bound, not a promise.
How do you check that a web worker fixed the freeze?
Watch for long tasks before and after the change. In Chromium-based browsers, a PerformanceObserver can log every main-thread task of 50 milliseconds or more.
new PerformanceObserver(function (list) {
list.getEntries().forEach(function (entry) {
console.log('long task:', Math.round(entry.duration), 'ms');
});
}).observe({ type: 'longtask', buffered: true });Add it near the top of the page. When we blocked the main thread for 120 milliseconds, it printed long task: 119 ms. With the worker version of the dashboard, it printed nothing for the parsing work.
This API exists only in Chromium-based browsers; Firefox and Safari do not ship it, per MDN compatibility data as of 31 October 2026. For other browsers, record a trace in the browser's performance panel instead.
- Test on a mid-range phone or with CPU slowdown turned on, because a fast laptop hides long tasks.
- Compare the longest task before and after, in milliseconds, not just the total time.
- Track INP from real users after release; good is 200 milliseconds or less at the 75th percentile.
How can a worker share memory instead of copying it?
Use a SharedArrayBuffer, a block of memory that both threads see at the same time. It avoids both copying and giving up ownership.
Browsers allow it only on a secure page (HTTPS or localhost) that is cross-origin isolated. That is a stricter mode the page turns on with two response headers. MDN says the global SharedArrayBuffer constructor is hidden otherwise, and our probe agreed: typeof SharedArrayBuffer was undefined.
These are the two headers. The second can also be credentialless instead of require-corp. With require-corp, cross-origin images and scripts load only if they opt in, through CORS (cross-origin resource sharing) or a Cross-Origin-Resource-Policy header.
Cross-Origin-Opener-Policy: same-origin
Cross-Origin-Embedder-Policy: require-corp// counter-worker.js
self.onmessage = function (event) {
var counter = new Int32Array(event.data);
for (var i = 0; i !== 1000; i++) Atomics.add(counter, 0, 1);
self.postMessage('done');
};var counterWorker = new Worker('counter-worker.js');
if (crossOriginIsolated) {
var shared = new SharedArrayBuffer(4);
counterWorker.onmessage = function () {
console.log('count:', Atomics.load(new Int32Array(shared), 0));
};
counterWorker.postMessage(shared);
} else {
console.log('not isolated: send an ArrayBuffer copy instead');
}With the headers, the console printed count: 1000. Without them, it printed the fallback line. Four workers each adding 1,000 through Atomics produced exactly 4000.
Atomics are operations that read and change shared memory as one step, so two threads cannot interleave halfway. Plain reads and writes on shared memory can race, which is a real source of bugs.
Web workers vs service workers vs shared workers
They share a name but solve different problems. A dedicated web worker does computation for one page; the others serve many pages or the network.
| Type | Who uses it | Main job | How long it lives |
|---|---|---|---|
| Dedicated worker | The one script that created it | Heavy computation off the main thread | Until the page closes or calls terminate |
| Shared worker | Several pages, tabs or frames from the same origin | One shared background helper | While any open page holds a reference to it |
| Service worker | All pages within its scope on the site | A proxy between pages and the network, for offline use and caching | Registered for an origin and path; it reacts to events such as page requests |
Shared workers became Baseline newly available in May 2026, meaning they work in the latest version of every major browser, per MDN as of 31 October 2026. If your problem is offline support or caching, read the SevyDevy guide on service workers. If it is a frozen page, you want a dedicated worker.
How do you explain web workers in a system design interview?
Walk from the symptom to the design, then name the costs. This frame fits a dashboard, an editor or an image tool.
Name the symptom with a number
Say which interaction is slow and how long the main thread is blocked, for example a 400 millisecond long task during filtering.
Split the roles
The main thread owns the page and input. One long-lived worker owns parsing, searching and sorting the data.
Design the messages
Requests carry a small command. Replies carry counts or one page of rows. Binary data moves as a transferred ArrayBuffer.
Plan the lifecycle
Start the worker once and reuse it. Size any pool from hardwareConcurrency. Handle onerror, and call terminate when the feature closes.
Prove it worked
Compare long tasks before and after, then track INP at the 75th percentile from real users.
Questions people ask
Do web workers make JavaScript run faster?
Not by themselves. A worker runs the same code on another thread. In our runs, parsing the 12.8 MB file took 43 to 51 ms in a worker and 41 to 58 ms on the main thread. The gain is that the page stays responsive while the work runs. A real speed-up needs the work split across several workers on a machine with spare cores, with small message costs.
Can a web worker access the DOM?
No. Inside a dedicated worker, document, window and localStorage are all undefined. The worker computes a result and posts it to the main thread, which then updates the page. A worker can draw on an OffscreenCanvas that the page handed over, which lets drawing run off the main thread.
Is res.json() already off the main thread?
Not in our test. In Chromium 153, fetching and parsing a 12.8 MB JSON file with res.json() and filtering it on the main thread produced one long task of 177 to 196 milliseconds. The promise only means you wait without blocking; the parsing work itself still landed on the main thread.
How many web workers should a page create?
Usually one long-lived worker, and rarely more than the number of cores. The HTML Standard calls workers heavy-weight, with high start-up and memory costs. navigator.hardwareConcurrency gives the logical processor count, though the browser may report fewer. Create workers once and reuse them, rather than starting one per job.
What is the difference between copying and transferring in postMessage?
Copying builds a duplicate on the other thread, and both sides keep a version. Transferring moves the memory itself, so the sender's buffer drops to zero bytes. In our Chromium run, transferring 64 MB took 0.5 milliseconds in postMessage, while copying took about 50 milliseconds.
Can I use import statements inside a web worker?
Yes, if you create a module worker by passing type set to module in the Worker options. Module workers shipped in Chrome 80, Firefox 114 and Safari 15. In a classic worker, an import statement fails with a SyntaxError, and the importScripts function is the classic way to load extra scripts.
Keep learning
Practise it with Lala
A question on this guide, hints and a review.
Read next
Sources (17)
- HTML Standard: Web workers (WHATWG)
- HTML Standard: Safe passing of structured data (WHATWG)
- MDN: Web Workers API
- MDN: Using Web Workers
- MDN: Worker() constructor
- MDN: The structured clone algorithm
- MDN: Transferable objects
- MDN: SharedArrayBuffer security requirements
- MDN: Cross-Origin-Embedder-Policy header
- MDN: SharedWorker
- MDN: Service Worker API
- MDN: Window.crossOriginIsolated
- MDN: PerformanceLongTaskTiming (long tasks)
- MDN: Navigator.hardwareConcurrency
- MDN: OffscreenCanvas
- web.dev: Interaction to Next Paint (INP)
- MDN browser-compat-data 8.1.7 (npm package)