Frontend development · Advanced · 30 min
Move heavy work off the main thread with a Web Worker
By Padding · Updated 18 Nov 2026
Node.js 26.13 · Vite 8.3.8 · Playwright 1.65.1 · checked in Chromium 159 on node:26
You will total a 100,000-row sales CSV in the browser, watch it freeze the page, then move the work into a Vite module worker that receives the file's bytes by transfer, reports progress, passes errors back and can be cancelled, with before and after measurements and a Playwright test to prove it.
On this page
Everything you write in a page's JavaScript runs on one thread, the main thread, which also handles clicks, key presses, layout and painting. While your code runs, nothing else does. A loop that takes half a second means half a second in which buttons do not respond, typing does not appear and animations driven by script stand still.
A Web Worker is a second JavaScript thread the page starts for you. It runs its own script, in its own global scope, and talks to the page only by passing messages. Give it the slow work, and the main thread stays free to respond.
You will build a small Vite page that totals a sales export: 100,000 rows of date,region,product,amount, about 4.3 MB of CSV. First you parse it on the main thread and measure the freeze. Then you move the parsing into a module worker, hand it the file's bytes without copying them, send progress back, return errors cleanly and let the reader cancel a run. A Playwright test checks the production build at the end, so you have numbers for before and after rather than an impression.
The same problem shows up hard on low-cost Android phones, which have slower processors and less memory than a developer laptop. A parse that takes a tenth of a second on your machine can stall a budget phone for much longer, so this is also a step towards a page that works for everyone on your users' real devices.
Step 1 · Create the project and a sample file
Scaffold a plain JavaScript project with create-vite, pinned so you get the same template, and pin Vite itself. Then remove the template's counter and images, which this page does not use:
cd ~
npm create vite@9.3.4 worker-demo -- --template vanilla --no-interactive
cd worker-demo
npm install --save-dev vite@8.3.8
rm src/counter.js
rm -r src/assetsYou need a big file to work on. Rather than downloading one, write a small Node.js script that generates it. It uses a seeded random number generator, so everyone who runs it gets exactly the same file, and it puts commas inside some quoted fields ("Lagos, Ikeja") and a non-ASCII character in a product name (Café latte), because real exports have both:
cd ~/worker-demo
cat > make-csv.mjs <<'JS'
// Writes a sales CSV with as many rows as you ask for.
// Usage: node make-csv.mjs <rows> <file>
import { writeFileSync } from 'node:fs';
const [rowsArg, file] = process.argv.slice(2);
const rows = Number(rowsArg);
if (!Number.isInteger(rows) || rows < 1 || !file) {
console.error('Usage: node make-csv.mjs <rows> <file>');
process.exit(1);
}
// A small seeded random number generator: the same command always writes the same file.
let seed = 2026;
function random() {
seed = (seed + 0x6d2b79f5) | 0;
let t = Math.imul(seed ^ (seed >>> 15), 1 | seed);
t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;
return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
}
const pick = (list) => list[Math.floor(random() * list.length)];
const regions = ['"Lagos, Ikeja"', '"Lagos, Lekki"', '"Nairobi, Westlands"', 'Accra', 'Kigali', 'Dakar'];
const products = ['Café latte', 'Jollof rice', 'Mandazi (6 pack)', 'Masala chai', '"Samosa, beef"', 'Bottled water'];
const lines = ['date,region,product,amount'];
for (let i = 0; i < rows; i++) {
const month = String(1 + Math.floor(random() * 12)).padStart(2, '0');
const day = String(1 + Math.floor(random() * 28)).padStart(2, '0');
const amount = (1 + random() * 499).toFixed(2);
lines.push(`2026-${month}-${day},${pick(regions)},${pick(products)},${amount}`);
}
writeFileSync(file, lines.join('\n') + '\n');
console.log(`Wrote ${rows.toLocaleString('en')} rows to ${file}`);
JS
node make-csv.mjs 100000 sales-100k.csv
head -n 4 sales-100k.csvCheck it worked
The script prints Wrote 100,000 rows to sales-100k.csv, and head shows the header and the first three rows:
date,region,product,amount
2026-06-09,Accra,Café latte,330.92
2026-03-20,"Lagos, Lekki",Café latte,400.90
2026-01-18,"Lagos, Ikeja",Jollof rice,195.02ls -lh sales-100k.csv reports about 4.1M (4.3 million bytes). ls src lists main.js and style.css only.
Step 2 · Total the file on the main thread
Start with the slow version, so you have something to measure. The parser reads the text one character at a time, which is what a CSV parser has to do to handle quoted commas correctly. It adds up amounts in whole cents, to avoid floating-point drift over 100,000 additions, and it throws an error naming the line when a row is malformed. Keep it in its own module: the worker will import the same file later.
cd ~/worker-demo
cat > src/parse-csv.js <<'JS'
// Totals a sales CSV with the header date,region,product,amount.
// Handles quoted fields such as "Lagos, Ikeja" and doubled quotes inside them.
export function totalSales(text, onProgress) {
if (text.charCodeAt(0) === 0xfeff) text = text.slice(1); // byte order mark from Excel
const byRegion = {};
let totalCents = 0;
let rows = 0;
let line = 1;
let fields = [];
let field = '';
let inQuotes = false;
let i = 0;
function endRow() {
fields.push(field);
field = '';
if (line === 1) {
if (fields.join(',') !== 'date,region,product,amount') {
throw new Error('Line 1: expected the header date,region,product,amount');
}
} else if (fields.length > 1 || fields[0] !== '') {
if (fields.length !== 4) {
throw new Error(`Line ${line}: expected 4 fields, found ${fields.length}`);
}
const [, region, , amount] = fields;
if (!/^\d+(\.\d{1,2})?$/.test(amount)) {
throw new Error(`Line ${line}: amount "${amount}" is not a number`);
}
const cents = Math.round(Number(amount) * 100);
totalCents += cents;
byRegion[region] = (byRegion[region] ?? 0) + cents;
rows++;
if (onProgress && rows % 10000 === 0) onProgress(i / text.length);
}
fields = [];
line++;
}
for (; i < text.length; i++) {
const ch = text[i];
if (inQuotes) {
if (ch === '"' && text[i + 1] === '"') { field += '"'; i++; }
else if (ch === '"') inQuotes = false;
else field += ch;
} else if (ch === '"') inQuotes = true;
else if (ch === ',') { fields.push(field); field = ''; }
else if (ch === '\n') endRow();
else if (ch !== '\r') field += ch;
}
if (field !== '' || fields.length > 0) endRow();
return { rows, totalCents, byRegion };
}
JSThe onProgress callback is optional and unused for now. It reports how far through the text the parser is, every 10,000 rows.
Now the page. It has a file picker, a button for each way of running the work, a progress bar, a status line, and two things that show whether the page is alive: a clock redrawn by JavaScript on every frame, and a "Tap me" button that counts presses.
cd ~/worker-demo
cat > index.html <<'HTML'
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Sales totals</title>
</head>
<body>
<main>
<h1>Sales totals</h1>
<p>Clock: <span id="clock" class="clock">0.0 s</span></p>
<label for="file">Sales CSV file</label>
<input id="file" type="file" accept=".csv,text/csv" />
<div class="actions">
<button id="run-main" type="button">Total on the main thread</button>
<button id="run-worker" type="button">Total in a worker</button>
<button id="cancel" type="button">Cancel</button>
</div>
<progress id="progress" max="100" value="0" aria-label="Progress"></progress>
<p id="status" role="status">Choose a CSV file.</p>
<button id="tap" type="button">Tap me (0)</button>
<h2>Result</h2>
<p>Rows: <span id="rows">none yet</span> · Total: <span id="total">none yet</span></p>
<table>
<caption>Sales by region</caption>
<tbody id="regions"></tbody>
</table>
<h2>Measurements</h2>
<ul id="log"></ul>
</main>
<script type="module" src="/src/main.js"></script>
</body>
</html>
HTML
cat > src/style.css <<'CSS'
body { margin: 0; font-family: system-ui, sans-serif; line-height: 1.5; color: #1b1f24; background: #f6f7f8; }
main { max-width: 40rem; margin: 0 auto; padding: 1rem; }
.clock { font-variant-numeric: tabular-nums; font-size: 1.5rem; font-weight: 600; }
.actions { display: flex; flex-wrap: wrap; gap: 0.5rem; margin: 1rem 0; }
button { min-height: 2.75rem; padding: 0 1rem; font: inherit; }
progress { width: 100%; }
table { border-collapse: collapse; width: 100%; }
td { padding: 0.25rem 0; border-bottom: 1px solid #d5d9df; }
td:last-child { text-align: right; font-variant-numeric: tabular-nums; }
CSSThe clock is drawn by JavaScript on purpose. Some CSS animations are run by the browser's compositor and keep moving while your script is blocked, which would hide the problem you are trying to see. The clock is not a live region, so screen readers do not announce it every frame; the status line is, so they hear "Done." or an error.
The script measures each run. While a run is active, every frame the browser draws is counted, and the longest gap between two frames is recorded. That gap is how long the page was frozen. Taps handled during the run are counted too.
cd ~/worker-demo
cat > src/main.js <<'JS'
import './style.css';
import { totalSales } from './parse-csv.js';
const $ = (selector) => document.querySelector(selector);
const fileInput = $('#file');
const progressBar = $('#progress');
const statusText = $('#status');
const clock = $('#clock');
const tapButton = $('#tap');
const money = new Intl.NumberFormat('en', { minimumFractionDigits: 2, maximumFractionDigits: 2 });
// The run being measured, or null when nothing is running.
let run = null;
let lastFrame = performance.now();
// A clock redrawn by JavaScript on every frame. It stops whenever the main thread is busy.
function drawFrame(now) {
clock.textContent = `${(now / 1000).toFixed(1)} s`;
if (run) {
run.frames++;
run.longestGap = Math.max(run.longestGap, now - lastFrame);
}
lastFrame = now;
requestAnimationFrame(drawFrame);
}
requestAnimationFrame(drawFrame);
let taps = 0;
tapButton.addEventListener('click', () => {
taps++;
tapButton.textContent = `Tap me (${taps})`;
if (run) run.taps++;
});
function setStatus(message) {
statusText.textContent = message;
}
function startRun(label) {
run = { label, start: performance.now(), frames: 0, longestGap: 0, taps: 0 };
}
function finishRun(result) {
const end = performance.now();
const longestGap = Math.round(Math.max(run.longestGap, end - lastFrame));
const ms = Math.round(end - run.start);
const item = document.createElement('li');
item.textContent = `${run.label}: ${result.rows.toLocaleString('en')} rows in ${ms} ms, ` +
`longest freeze ${longestGap} ms, ${run.frames} frames drawn, ${run.taps} taps handled while working`;
Object.assign(item.dataset, { label: run.label, ms, longestGap, frames: run.frames, taps: run.taps });
$('#log').append(item);
run = null;
}
function showResult(result) {
$('#rows').textContent = result.rows.toLocaleString('en');
$('#total').textContent = money.format(result.totalCents / 100);
const rows = Object.entries(result.byRegion)
.sort((a, b) => b[1] - a[1])
.map(([region, cents]) => {
const tr = document.createElement('tr');
const name = document.createElement('td');
const amount = document.createElement('td');
name.textContent = region;
amount.textContent = money.format(cents / 100);
tr.append(name, amount);
return tr;
});
$('#regions').replaceChildren(...rows);
}
$('#run-main').addEventListener('click', async () => {
const file = fileInput.files[0];
if (!file) return setStatus('Choose a CSV file first.');
if (run) return;
const text = await file.text();
setStatus('Working on the main thread…');
startRun('Main thread');
try {
const result = totalSales(text);
finishRun(result);
showResult(result);
setStatus('Done.');
} catch (error) {
run = null;
setStatus(error.message);
}
});
JSReading the file with file.text() is asynchronous and does not block. The measurement starts after it, so it times only the parsing. The Worker and Cancel buttons do nothing yet.
Start the dev server and leave it running in its own terminal:
npm run devCheck it worked
Open the Local: address Vite prints, usually http://localhost:5173/. The clock counts up in tenths of a second. Choose sales-100k.csv in ~/worker-demo, click Total on the main thread, then quickly click Tap me a few times.
- The result reads
Rows: 100,000 · Total: 24,968,103.44, with six regions in the table, Dakar at the top. - The "Working on the main thread…" message never appears. The browser had no chance to paint it before the work started, and by the time it could, the status was already "Done."
- The Measurements list gains a line like
Main thread: 100,000 rows in 104 ms, longest freeze 110 ms, 0 frames drawn, 0 taps handled while working. Your milliseconds will differ. The0 frames drawnwill not: no frame can be drawn while the parser holds the main thread. Your taps were queued and handled afterwards, so the counter jumps all at once.
On a fast laptop the freeze is short enough to miss. To feel what a slower phone feels, open DevTools, go to the Performance panel, set CPU throttling to a 4x or 6x slowdown in its capture settings, and run it again: the clock visibly stops and the freeze grows several times over. Turn throttling back off when you are done.
Step 3 · Move the parsing into a module worker
A worker is a separate script. Create src/csv-worker.js. It listens for a message, runs the same totalSales function on the text it receives, and posts the result back:
cd ~/worker-demo
cat > src/csv-worker.js <<'JS'
import { totalSales } from './parse-csv.js';
self.addEventListener('message', (event) => {
self.postMessage(totalSales(event.data));
});
JSself is the worker's global scope, the counterpart of window in the page. Because this is a module worker, it can use import, so the parser is shared rather than copied.
On the page side, put the worker handling in a small module of its own. The line that starts the worker is the important one:
cd ~/worker-demo
cat > src/run-in-worker.js <<'JS'
const worker = new Worker(new URL('./csv-worker.js', import.meta.url), { type: 'module' });
export async function runInWorker(file) {
const text = await file.text();
return new Promise((resolve) => {
worker.addEventListener('message', (event) => resolve(event.data), { once: true });
worker.postMessage(text);
});
}
JSWrite the worker's address exactly in that form: new URL('./csv-worker.js', import.meta.url) inside new Worker(...). Vite recognises the pattern. In development it serves the worker as a module; in a build it bundles the worker and everything it imports into a separate file and rewrites the address to point at it. A plain string such as new Worker('/src/csv-worker.js') works in development and then breaks in the build. { type: 'module' } tells the browser the worker uses import.
postMessage sends a copy of the data, made with the structured clone algorithm. The page and the worker never share the same object, which is why they cannot step on each other. The result comes back the same way, as a copied plain object.
Now wire the Worker button. Append this block to src/main.js. It already handles progress and errors, which the worker learns to send in later steps:
cd ~/worker-demo
cat >> src/main.js <<'JS'
// Runs the same work in a module worker.
import { runInWorker } from './run-in-worker.js';
$('#run-worker').addEventListener('click', async () => {
const file = fileInput.files[0];
if (!file) return setStatus('Choose a CSV file first.');
if (run) return;
setStatus('Working in a worker…');
progressBar.value = 0;
startRun('Worker');
try {
const result = await runInWorker(file, (fraction) => {
progressBar.value = Math.round(fraction * 100);
});
progressBar.value = 100;
finishRun(result);
showResult(result);
setStatus('Done.');
} catch (error) {
run = null;
setStatus(error.message);
}
});
JSHere the measurement includes reading the file, since runInWorker does it. That is fair: reading is asynchronous, so it does not block either.
Check it worked
The page reloads by itself. Choose sales-100k.csv again, click Total in a worker and tap Tap me while it runs.
- "Working in a worker…" appears this time, because the main thread is free to paint it.
- The clock keeps counting and every tap registers straight away.
- The new measurement line reads something like
Worker: 100,000 rows in 131 ms, longest freeze 17 ms, 8 frames drawn, 2 taps handled while working. The total time can be the same or a little longer than on the main thread: the work did not get faster, it moved. What changed is the longest freeze, now about one frame (17 ms at 60 frames per second), and the frames drawn, now above zero.
With CPU throttling on, the difference is larger: the main-thread freeze grows with the slowdown, and the worker run stays smooth.
Step 4 · Check what a worker cannot touch
A worker has no document, no window and no DOM at all. It cannot read an element, set textContent or add a class. It also lacks localStorage. That is why the worker returns plain data and main.js builds the table: the rule is that the worker computes and the page renders.
Workers do get a lot of the platform: fetch, timers, IndexedDB, WebSocket, crypto, TextDecoder and module imports, among others. A worker can fetch and process data on its own and send back only the summary.
See it for yourself in DevTools. Open the Console panel. At the top of the console is the JavaScript context menu, which normally says top. Open it and choose csv-worker.js: from now on, what you type runs inside the worker. Type each of these and press Enter:
typeof document
typeof fetchCheck it worked
In the worker context, typeof document returns 'undefined' and typeof fetch returns 'function'. Typing document.title gives ReferenceError: document is not defined. Switch the menu back to top and typeof document returns 'object' again. If csv-worker.js is missing from the menu, reload the page: run-in-worker.js starts the worker as soon as the page loads.
Step 5 · Transfer the bytes instead of copying the text
Copying is fine for small messages. For a whole file it has costs: the 4.3 MB text exists twice in memory for a moment, once on each side, and the copy itself takes main-thread time. On a phone with 2 GB of memory and a 40 MB export, both matter.
Some objects can be transferred instead of copied. An ArrayBuffer, a block of raw bytes, is one of them. Transferring hands the bytes to the worker without copying them, and the page's buffer becomes empty and unusable, since only one side may own it. Strings cannot be transferred, so read the file as bytes and let the worker decode them.
Rewrite src/run-in-worker.js to read an ArrayBuffer and list it in postMessage's second argument, the transfer list:
cd ~/worker-demo
cat > src/run-in-worker.js <<'JS'
const worker = new Worker(new URL('./csv-worker.js', import.meta.url), { type: 'module' });
export async function runInWorker(file) {
const bytes = await file.arrayBuffer();
return new Promise((resolve) => {
worker.addEventListener('message', (event) => resolve(event.data), { once: true });
worker.postMessage(bytes, [bytes]);
console.log('After postMessage, bytes.byteLength is', bytes.byteLength);
});
}
JS
cat > src/csv-worker.js <<'JS'
import { totalSales } from './parse-csv.js';
self.addEventListener('message', (event) => {
const text = new TextDecoder('utf-8').decode(event.data);
self.postMessage(totalSales(text));
});
JSThe decoding now happens in the worker too, off the main thread. TextDecoder reads UTF-8 by default, which is what the generator writes and what most tools export today. If your users export from older spreadsheet software in a legacy encoding, TextDecoder accepts others, such as 'windows-1252', so names with accents or other scripts come through intact.
You do not always need a buffer. A File object can itself be posted to a worker; the clone refers to the same file on disk, so the worker can call file.arrayBuffer() itself. Transferring an ArrayBuffer is the general tool for bytes the page already holds, such as a download or a canvas's pixels.
Check it worked
Open the DevTools console in the top context, choose the file and click Total in a worker. The console prints After postMessage, bytes.byteLength is 0: the buffer moved to the worker and the page's copy is now detached. The result is the same as before, 24,968,103.44, including the Café latte rows, which shows the decoding is right.
Step 6 · Report progress and return errors
Two things are still missing. A long run should show progress, and a bad file should give a clear message rather than a promise that never settles.
Give every message from the worker a type, so the page can tell progress from results from errors. Send progress through the parser's onProgress callback, every 10,000 rows. Posting a message for every row would flood the main thread with 100,000 messages and undo the point of the worker. Wrap the work in try/catch and send an error message back:
cd ~/worker-demo
cat > src/csv-worker.js <<'JS'
import { totalSales } from './parse-csv.js';
self.addEventListener('message', (event) => {
try {
const text = new TextDecoder('utf-8').decode(event.data);
const result = totalSales(text, (fraction) => {
self.postMessage({ type: 'progress', fraction });
});
self.postMessage({ type: 'result', result });
} catch (error) {
self.postMessage({ type: 'error', message: error.message });
}
});
JSOn the page side, keep one listener per worker and route each message to the run in progress. Listen for the worker's error event as well. It fires for an error the worker did not catch, and when the worker script fails to load, for example because of a wrong path. The worker is now started on first use rather than when the page loads, so a page visit that never totals a file never starts a thread:
cd ~/worker-demo
cat > src/run-in-worker.js <<'JS'
let worker = null;
let pending = null; // { resolve, reject, onProgress } for the run in progress
function startWorker() {
worker = new Worker(new URL('./csv-worker.js', import.meta.url), { type: 'module' });
worker.addEventListener('message', (event) => {
const message = event.data;
if (!pending) return;
if (message.type === 'progress') pending.onProgress(message.fraction);
else if (message.type === 'result') settle().resolve(message.result);
else if (message.type === 'error') settle().reject(new Error(message.message));
});
// Fires for an error the worker did not catch, or when the worker script cannot load.
worker.addEventListener('error', (event) => {
if (pending) settle().reject(new Error(`The worker failed: ${event.message || 'it could not start'}`));
});
}
function settle() {
const current = pending;
pending = null;
return current;
}
export async function runInWorker(file, onProgress) {
if (!worker) startWorker();
const bytes = await file.arrayBuffer();
return new Promise((resolve, reject) => {
pending = { resolve, reject, onProgress };
worker.postMessage(bytes, [bytes]);
console.log('After postMessage, bytes.byteLength is', bytes.byteLength);
});
}
JSThe error is sent as a plain message string. It reaches main.js as a rejected promise, where the catch in the Worker button's handler puts it in the status line.
Make a file with a bad amount on line 3 to try it:
cd ~/worker-demo
cat > bad.csv <<'CSV'
date,region,product,amount
2026-01-05,Accra,Masala chai,2.50
2026-01-06,Kigali,Bottled water,abc
CSVCheck it worked
Choose sales-100k.csv and click Total in a worker. The progress bar fills in steps rather than jumping from empty to full. Then choose bad.csv and click Total in a worker: the status line reads Line 3: amount "abc" is not a number, and nothing new is added to Measurements. Total on the main thread with the same file gives the same message, because both paths share the parser.
Step 7 · Cancel a run with terminate
A worker that is working through a large file cannot be interrupted by a message: it only reads its messages when the current one is finished. To stop it, the page calls worker.terminate(), which ends the thread at once, with no chance to clean up. A terminated worker cannot be started again, so the next run creates a fresh one. (A worker can also stop itself by calling self.close().)
Append a cancelWorker function to src/run-in-worker.js, and a handler for the Cancel button to src/main.js:
cd ~/worker-demo
cat >> src/run-in-worker.js <<'JS'
// Stops the worker part-way. A terminated worker cannot be restarted, so the next run starts a new one.
export function cancelWorker() {
if (!pending) return false;
worker.terminate();
worker = null;
settle().reject(new Error('Cancelled.'));
return true;
}
JS
cat >> src/main.js <<'JS'
// Lets the reader stop a run part-way.
import { cancelWorker } from './run-in-worker.js';
$('#cancel').addEventListener('click', () => {
if (!cancelWorker()) setStatus('Nothing to cancel.');
});
JSThe rejected promise lands in the same catch as an error, so the status line reads Cancelled. and no result is recorded. Only the worker run can be cancelled. A main-thread run cannot: while it works, the Cancel click waits in the queue with everything else.
To have time to press Cancel, make a file ten times bigger, about 43 MB:
cd ~/worker-demo
node make-csv.mjs 1000000 sales-1m.csvCheck it worked
Choose sales-1m.csv, click Total in a worker, and click Cancel while the progress bar is moving. The bar stops, the status reads Cancelled. and no line is added to Measurements. Click Total in a worker again and let it finish: a new worker starts and the result shows 1,000,000 rows. Now try Total on the main thread with the same file and press Cancel during it: nothing happens until the run is over, then the status says Nothing to cancel.
Step 8 · Build the page and test it in a browser
Checking by hand proves it once. A test proves it every time someone changes the code, and it checks the production build, where Vite has bundled the worker into a file of its own.
Install Playwright into the project, pinned, plus the Chromium it drives. --with-deps also installs the system libraries Chromium needs on Linux and can ask for your password:
cd ~/worker-demo
npm install --save-dev playwright@1.65.1
npx playwright install --with-deps chromiumThe test starts Vite's preview server from its JavaScript API, so one command does everything. It computes the expected answer in Node.js with the same parse-csv.js, then drives the page: the main-thread run, the worker run, the one-million-row comparison with a tap during the worker run, a cancel, the bad file, and a final run to prove a fresh worker starts after a cancel:
cd ~/worker-demo
cat > test-worker.mjs <<'JS'
import { chromium } from 'playwright';
import { preview } from 'vite';
import assert from 'node:assert/strict';
import { readFileSync } from 'node:fs';
import { totalSales } from './src/parse-csv.js';
const money = new Intl.NumberFormat('en', { minimumFractionDigits: 2, maximumFractionDigits: 2 });
const expected = totalSales(readFileSync('sales-100k.csv', 'utf8'));
const expectedTotal = money.format(expected.totalCents / 100);
const server = await preview({ preview: { port: 4173, strictPort: true }, logLevel: 'silent' });
const browser = await chromium.launch();
try {
const page = await browser.newPage();
const consoleLines = [];
page.on('console', (message) => consoleLines.push(message.text()));
await page.goto('http://localhost:4173/');
const log = page.locator('#log li');
const statusText = page.locator('#status');
const runMain = page.getByRole('button', { name: 'Total on the main thread' });
const runWorker = page.getByRole('button', { name: 'Total in a worker' });
const progressAboveZero = () => page.waitForFunction(() => document.querySelector('#progress').value > 0);
const entry = (n) => log.nth(n).evaluate((li) => ({ ...li.dataset }));
// 1. Main thread, 100,000 rows: the right answer, and no frames drawn while it ran.
await page.locator('#file').setInputFiles('sales-100k.csv');
await runMain.click();
await log.nth(0).waitFor();
assert.equal(await page.locator('#rows').textContent(), '100,000');
assert.equal(await page.locator('#total').textContent(), expectedTotal);
assert.equal((await entry(0)).frames, '0', 'the main thread drew no frames while working');
// 2. Worker, same file: same answer, no DOM in the worker, and the buffer was transferred.
const workerStarted = page.waitForEvent('worker');
await runWorker.click();
const worker = await workerStarted;
await log.nth(1).waitFor();
assert.equal(await page.locator('#total').textContent(), expectedTotal);
assert.equal(await page.locator('#regions tr').count(), 6);
assert.equal(await worker.evaluate(() => typeof document), 'undefined');
assert.equal(await worker.evaluate(() => typeof postMessage), 'function');
assert.ok(consoleLines.includes('After postMessage, bytes.byteLength is 0'), 'the buffer was transferred');
// 3. One million rows: before and after, with a tap during the worker run.
await page.locator('#file').setInputFiles('sales-1m.csv');
await runMain.click();
await log.nth(2).waitFor();
await runWorker.click();
await progressAboveZero();
await page.getByRole('button', { name: /^Tap me/ }).click();
await log.nth(3).waitFor();
const before = await entry(2);
const after = await entry(3);
assert.equal(before.frames, '0');
assert.ok(Number(after.frames) >= 3, `the worker run drew ${after.frames} frames`);
assert.ok(Number(after.taps) >= 1, 'a tap was handled while the worker was busy');
assert.ok(Number(after.longestGap) < Number(before.longestGap), 'the worker run froze the page for less time');
console.log(`1,000,000 rows. Main thread: longest freeze ${before.longestGap} ms. Worker: longest freeze ${after.longestGap} ms.`);
// 4. Cancel part-way: the status says so and no result arrives later.
await runWorker.click();
await progressAboveZero();
await page.getByRole('button', { name: 'Cancel' }).click();
assert.equal(await statusText.textContent(), 'Cancelled.');
await page.waitForTimeout(1500);
assert.equal(await statusText.textContent(), 'Cancelled.');
assert.equal(await log.count(), 4, 'a cancelled run records nothing');
// 5. A bad file: the worker's error reaches the status line.
await page.locator('#file').setInputFiles('bad.csv');
await runWorker.click();
await page.getByText('Line 3: amount "abc" is not a number').waitFor();
// 6. After a cancel and an error, a new run still works.
await page.locator('#file').setInputFiles('sales-100k.csv');
await runWorker.click();
await log.nth(4).waitFor();
assert.equal(await page.locator('#total').textContent(), expectedTotal);
} finally {
await browser.close();
await server.close();
}
console.log('PASS: the worker keeps the page responsive');
JS
npm run build
ls dist/assets
node test-worker.mjsnpm run build writes the site to dist, and preview() serves that folder on port 4173 for the length of the test.
Check it worked
ls dist/assets lists a csv-worker- file with a hash in its name, next to the page's own JavaScript and CSS: Vite bundled the worker and the parser it imports into one file. The test prints a line comparing the two runs on one million rows, something like Main thread: longest freeze 1210 ms. Worker: longest freeze 34 ms. (your numbers will differ), and finishes with PASS: the worker keeps the page responsive. To see the test fail for the right reason, change { type: 'progress', fraction } in src/csv-worker.js to { type: 'progress', fraction: 0 }, run npm run build and node test-worker.mjs again: it times out waiting for progress. Put the line back afterwards.
Step 9 · Clean up
Stop the dev server with Ctrl+C in its terminal. Then remove the demo folder, which also removes the local Vite and Playwright installs and the two CSV files. The Chromium build Playwright downloaded stays in its shared cache; npx playwright uninstall removes it if you no longer need it.
cd ~
rm -rf ~/worker-demoCheck it worked
ls ~/worker-demo reports that there is no such file or directory.
Next steps
- Measure and fix slow responses to clicks and key presses on the main thread itself in speed up slow interactions and improve INP.
- Learn more of what Vite does with your files, in development and in a build, in start a plain JavaScript project with Vite.
- Record a performance profile and step through worker code in debug JavaScript in Chrome DevTools.
- Grow the test into a proper suite with the Playwright test runner in write end-to-end browser tests with Playwright.
Related tutorials
- Speed up slow interactions and improve Interaction to Next PaintYou will take a filter box that freezes the page on every key press, measure each interaction's input delay, processing time and presentation delay, and fix it by batching layout reads and writes, yielding to the browser, chunking the work and debouncing it, until a scripted measurement on a slowed-down CPU shows the worst interaction under 200 ms.
- Start and build a plain JavaScript project with Vite 8You will scaffold a plain JavaScript project with Vite 8, watch hot updates in the dev server, import CSS and an image, read VITE_ settings, serve fixed files from public, and ship a hashed production build that works from a sub-folder.
- Debug JavaScript in Chrome DevTools with breakpoints and the consoleYou will find and fix two planted bugs in a small basket page, a wrong total and a voucher request that fails without a word, using the Console, breakpoints, logpoints, stepping, the Scope, Watch and Call Stack panes and the Network panel.
Need this done for you?
Padding does this work for growing companies, from the first diagnosis to a system that keeps working.
Get new tutorials