Skip to content
Tech Atlas, home
Search
Esc
  • All roadmapsBrowse every learning path
  • ExploreFind a technology area
  • ProjectsGuided projects and builds
  • My AtlasYour learning dashboard
Lesson 2 of 6 · Worked example · 20 min · revision 3

Off the Main Thread with Web Workers

Move a heavy parse-and-filter into a Web Worker, measure the main-thread long tasks that disappear, and learn what posting messages really costs.

Contentsand lesson path

What you will learn

  • Move CPU-heavy work such as parsing or filtering a large dataset into a Web Worker with message passing, and show the gain in input responsiveness in a Performance trace.

Prerequisites: Async JavaScript & Fetch

01. The problem: a long task on the main thread

The browser runs your JavaScript, layout, painting and input handling on one main thread per page. Any task that holds that thread for more than 50 ms is a long task, and a burst of them is what users experience as jank: keystrokes that echo late, a list that scrolls roughly. The browser cannot process input while your code runs, however important your code is.

The worked example here is a common shape: an import of 250,000 records arrives as one 20 MB JSON string, and the page needs the records whose price is at least 4500. Parsing and filtering on the main thread looks innocent and works — while blocking everything else. How rendering works and the long-task and INP material in /skills/web-performance cover the rendering side; this lesson moves the work off the thread.

A Web Worker is a second JavaScript thread for exactly this. It runs a script of its own, with no access to the DOM, and communicates with the page by passing messages. The plan: measure the damage on the main thread, repeat the work in a worker, compare, then look honestly at what messaging itself costs.

JavaScript · build the payload, then parse and filter on the main thread
const log = (label, value) => console.log(label + ': ' + value);

const records = Array.from({ length: 250000 }, (_, i) => ({
  id: i,
  name: 'item ' + i + ' colour ' + ['red', 'green', 'blue', 'amber'][i % 4],
  price: (i * 7919) % 5000,
  tags: [i % 2 ? 'sale' : 'new', 'cat-' + (i % 50)],
}));
const payload = JSON.stringify(records);
log('payload size', (payload.length / 1048576).toFixed(1) + ' MB of JSON');

const heavy = (text) => JSON.parse(text)
  .filter((r) => r.price >= 4500)
  .map((r) => r.name);

let longTasks = 0;
new PerformanceObserver((list) => { longTasks += list.getEntries().length; })
  .observe({ type: 'longtask', buffered: true });

const t0 = performance.now();
const mainHits = heavy(payload);
const mainMs = Math.round(performance.now() - t0);
await new Promise((r) => setTimeout(r, 400)); // let callbacks and GC settle
log('main thread: parse + filter', mainMs + ' ms, ' + mainHits.length + ' hits');
log('main thread long tasks (>50 ms)', longTasks);
Illustrative output (one run in headless Chromium 156 on a shared test machine; timings vary)
payload size: 19.9 MB of JSON
main thread: parse + filter: 109 ms, 25000 hits
main thread long tasks (>50 ms): 1

One task of 109 ms in this run: the page was unresponsive for about twice the 50 ms budget while JSON.parse plus the filter ran. The PerformanceObserver counting long tasks is the scripted stand-in for what DevTools shows visually, and the 400 ms settle keeps unrelated work out of the count. The same measurement after the fix is the evidence that the fix worked.

02. Step 1: the same work in a worker

A worker is a separate script file (same origin as the page) loaded with new Worker(url). It listens for messages with self.onmessage and replies with postMessage. Everything it does happens on its own thread; it cannot touch the DOM. This worker handles three message shapes: a JSON string to parse and filter, binary buffers to acknowledge, and an object to echo back so we can inspect what survives the trip.

JavaScript · filter-worker.js
let workerT0 = 0;
self.onmessage = (event) => {
  const data = event.data;
  if (typeof data === 'string') {
    workerT0 = performance.now();
    const rows = JSON.parse(data);
    const hits = rows.filter((r) => r.price >= 4500).map((r) => r.name);
    postMessage({ hits, took: performance.now() - workerT0 });
    return;
  }
  if (data instanceof ArrayBuffer || ArrayBuffer.isView(data)) {
    postMessage('got buffer of ' + data.byteLength + ' bytes');
    return;
  }
  if (data && data.at instanceof Date) {
    postMessage('Date ' + data.at.toISOString()
      + ', Set size ' + data.tags.size + ', Map get k = ' + data.meta.get('k'));
    return;
  }
  if (Array.isArray(data)) {
    postMessage('got ' + data.length + ' rows');
    return;
  }
  postMessage({ error: 'unexpected message' });
};
JavaScript · hand the payload to the worker
const worker = new Worker('/filter-worker.js');
const before = longTasks;
const t1 = performance.now();
const workerHits = await new Promise((resolve, reject) => {
  worker.onmessage = (e) => (e.data.error
    ? reject(new Error(e.data.error))
    : resolve(e.data.hits));
  worker.postMessage(payload);
});
log('worker: parse + filter', Math.round(performance.now() - t1)
  + ' ms, ' + workerHits.length + ' hits');
log('long tasks during the worker phase', longTasks - before);
log('same hits?', JSON.stringify(workerHits) === JSON.stringify(mainHits));
Illustrative output (one run in headless Chromium 156 on a shared test machine; timings vary)
worker: parse + filter: 255 ms, 25000 hits
long tasks during the worker phase: 0
same hits?: true

Read those three lines as the whole argument. The work itself got slower — 255 ms in the worker against 109 ms on the main thread in the same run, because the worker starts cold (its script has to be fetched and its code is not yet optimised) and the 20 MB string goes in and the 25,000 names come back as copies. But the main thread recorded no long task while the worker ran, and the result is identical. The point of a worker is not speed; it is a free main thread: while the worker parsed, the main thread stayed available for input handling and painting.

03. Step 2: what messages cost

Messages are copied, not shared. postMessage serialises the value with the structured clone algorithm and the other side deserialises it — and the serialisation runs on the sending thread, so a big message is itself a main-thread cost. Structured clone is far more capable than JSON (Dates, Maps, Sets, ArrayBuffers and typed arrays all survive; functions and DOM nodes do not), but it is not free. Three measurements make the costs concrete. The worker answers every message, so the demo installs a reply handler before each post and awaits that reply before posting again; otherwise a late reply to one message would be read as the answer to the next:

JavaScript · the price of posting
// One helper: install the reply handler, then post, then await the reply.
const reply = () => new Promise((r) => { worker.onmessage = (e) => r(e.data); });

let next = reply();
const t2 = performance.now();
worker.postMessage(records);
log('posting 250,000 objects cost the main thread',
  (performance.now() - t2).toFixed(1) + ' ms');
log('worker acknowledged', await next);

const shared = new Uint8Array(20 * 1024 * 1024);
next = reply();
const t3 = performance.now();
worker.postMessage(shared);
log('postMessage 20 MB (copied)', (performance.now() - t3).toFixed(1) + ' ms');
await next;

const moved = new Uint8Array(20 * 1024 * 1024);
next = reply();
const t4 = performance.now();
worker.postMessage(moved, [moved.buffer]);
log('postMessage 20 MB (transferred)', (performance.now() - t4).toFixed(1) + ' ms');
await next;
log('source buffer after transfer', moved.buffer.byteLength + ' bytes (detached)');

next = reply();
worker.postMessage({ at: new Date(0), tags: new Set(['a', 'b']),
  meta: new Map([['k', 1]]) });
log('structured clone round trip', await next);
worker.terminate();
Illustrative output (one run in headless Chromium 156 on a shared test machine; timings vary)
posting 250,000 objects cost the main thread: 267.7 ms
worker acknowledged: got 250000 rows
postMessage 20 MB (copied): 18.9 ms
postMessage 20 MB (transferred): 0.1 ms
source buffer after transfer: 0 bytes (detached)
structured clone round trip: Date 1970-01-01T00:00:00.000Z, Set size 2, Map get k = 1

The worst line is the first: posting the 250,000 small objects cost the main thread about 268 ms in this run — more than twice the 109 ms of work we were escaping. Deep object graphs clone one property at a time; flat binary does not. The 20 MB Uint8Array copied in about 19 ms, and the same buffer transferred took 0.1 ms: putting its ArrayBuffer in the transfer list hands ownership to the worker instead of copying, which is why the source buffer reads as 0 bytes afterwards — it is detached and no longer usable on this side. Transfers are the tool for large binary payloads (file bytes, pixel data, audio chunks); they only work on ArrayBuffers and a few similar types, and the sent buffer must be the one in the transfer list.

So the practical shape of the pattern: workers receive raw input (strings, transferred buffers) and return small results. If you find yourself posting 250,000 objects somewhere, restructure the work so the big data never crosses the thread boundary — parse inside the worker, or fetch inside it.

To show the gain the way a team would present it, record a trace: open DevTools, Performance panel, press record, run the import, stop. In the "before" recording the Main thread row shows the long task with its red corner marker, and the Interaction track shows typing delayed behind it. In the "after" recording the parse appears on its own worker track while the Main thread row stays clear, and interactions complete promptly. The PerformanceObserver counters in this lesson measure exactly what those red markers count, which is why "long tasks: 1 → 0" is honest evidence rather than a vibe.

04. Check your understanding

Practice check · 3 questions

Workers in practice

Three decisions from the pattern above.

Q1. Which of these tasks is a poor fit for a Web Worker, even though it is heavy?
Q2. Which message can be posted to a worker as it is?
Q3. Posting 250,000 small objects to the worker cost the main thread about 268 ms in the run above, before the worker did any work. Where did that time go?
Practice only: not graded, not saved, not evidence.

05. Apply it

The skill's practice task includes "parse large imports in a Web Worker". Take an import your notes app might receive — a JSON file of archived notes — and:

  1. Measure the main-thread cost of JSON.parse on it, with a long-task counter as above.
  2. Move the parse and validation into a worker that receives the raw text and answers with a small report (count, first error found).
  3. Send the parsed records into IndexedDB from the page (or, if you use a module worker, import your database helper there) and measure the whole flow before and after.
  4. Record both traces in the Performance panel and note what a teammate would see in each.

06. Review prompt

Without looking back: what can a Web Worker not do, and why is that not a problem for the filter case? What did the long-task counter show before and after the move, and why did the worker version still take longer in total? What is the structured clone algorithm, which types survive it, and how does a transfer list change both the cost and the source buffer?

References

Your progress

Reading state

Sign in to save that you finished reading this lesson.

Sign in to mark reading complete

Prove this skill

8 questions · about 6 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.
Take the skill check