JavaScript Web Workers: Offloading Heavy Computation
When a computation is too heavy for the main thread, Web Workers are the answer. Here is how I structure worker code. The main thread runs your JavaScript, handles user input, and paints the screen. Anything that blocks it for more than fifty milliseconds causes visible jank. For genuinely heavy computation, the only correct solution is to move it off the main thread, and Web Workers are the built-in mechanism for that. A worker runs in a separate thread with its own event loop, communicating with the main thread via message passing. Creating a Dedicated Worker A dedicated worker is created from a separate script file. The main thread posts messages to the worker, and the worker posts messages back. Data is copied when it crosses the boundary, with a few exceptions like transferable objects. The communication is asynchronous, so you design around promises and callbacks rather than direct function calls. // main.js const worker = new Worker('worker.js'); worker.onmessage = (e) => console.log('result', e.data); worker.postMessage({ input: largeArray }); // worker.js self.onmessage = (e) => { const result = heavyCompute(e.data.input); self.postMessage(result); }; Transferable Objects Avoid Copying By default, posting a message copies the…