Web Worker / offloading the main thread

A separate browser thread for heavy JavaScript, keeping the main thread free to paint, scroll, and answer taps.

run javascript without freezing the pagemove heavy calculation off the ui threadbackground thread in the browserkeep clicks responsive during a big loopweb workerweb wokrerimporting a big csv locks up the tabwhy can't my worker access the dom

See it

Live demo coming soon

What it is

A Web Worker runs JavaScript on a background thread so CPU-heavy work does not block clicks, scrolling, or painting on the main thread. The page and worker communicate with 'postMessage'; most values are copied with the structured clone algorithm, while transferable objects such as 'ArrayBuffer' can move without copying their bytes.

Use a worker for parsing a large file, image processing, search indexing, compression, or expensive calculations. Keep DOM reads and writes on the main thread because a worker has no direct access to 'document' or page elements.

Gotcha: messaging and startup have overhead. Moving a tiny function to a worker can be slower, and repeatedly cloning a large object can erase the responsiveness win. Send coarse jobs, transfer large binary buffers when ownership can move, and define explicit success, error, progress, and cancellation messages.

Ask AI for it

Move this CPU-heavy operation into a dedicated Web Worker created with new Worker(new URL('./worker.ts', import.meta.url), { type: 'module' }). Define typed 'postMessage' messages for start, progress, result, error, and cancel. Keep every DOM update on the main thread. When input or output contains an 'ArrayBuffer', include it in the transfer list instead of cloning it. Terminate the worker when its owner unmounts, reject pending jobs on worker errors, and compare the longest main-thread task and INP before and after with Chrome DevTools. If the hand-written message protocol turns into a switch statement nobody wants to touch, wrap the worker in Comlink and call it like a normal async module instead.

You might have meant

main thread blockinglong tasktotal blocking timeinteraction to next paintoffscreen canvas worker rendering

Go deeper