Skip to content
jshacks.dev
Performance

Use web workers for heavy parsing

Run a CPU-heavy parsing job such as CSV in a Web Worker and send the rows back with postMessage, so the page keeps responding while it works.

1 min read
Summarize in AI

Parsing a large CSV or Markdown file on the main thread blocks input until it finishes. A worker has its own thread, so the page stays interactive.

csv-worker.jsJavaScript
self.onmessage = ({ data: text }) => {
  const rows = text
    .trim()
    .split('\n')
    .map((line) => line.split(','));
  self.postMessage({ count: rows.length, first: rows[0] });
};
main.jsJavaScript
const worker = new Worker(new URL('./csv-worker.js', import.meta.url));

worker.onmessage = ({ data }) => {
  console.log(`parsed ${data.count} rows, first:`, data.first);
  worker.terminate();
};

worker.postMessage('id,name\n1,Ada\n2,Grace');
Text
parsed 3 rows, first: [ 'id', 'name' ]

new URL('./csv-worker.js', import.meta.url) is the form that bundlers such as Vite recognise and package as a separate file. Data goes in and out by postMessage, which copies it; for large binary data, transfer an ArrayBuffer in the second argument to move it with no copy.

Workers cannot touch the DOM, and each one costs memory and start-up time, so keep a long-lived one for repeated jobs instead of creating one per task. Call terminate() when done. This split on commas ignores quoted fields, so use a real CSV parser in practice. See Web Workers API.

Also inBrowser
Share

More snippets

Performance

Time code with performance.now

Time a block of code with performance.now, which returns a monotonic high-resolution timestamp in milliseconds, and avoid the clock jumps Date.now can have.

1 min read
APIs

Fetch JSON and handle HTTP errors

Fetch JSON in the browser or Node.js 24 and throw on 404 or 500 yourself, because fetch only rejects on network failure and does not check the status.

1 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.