Keep the Browser Responsive with Web Workers

A browser can download an asset, update a progress bar and open a menu in a fraction of a second. It can also spend several seconds performing a calculation, decoding an image or sorting a large collection without responding to a click. That pause is often called UI freeze, and it becomes especially damaging when the same interface is used for live dashboards, data imports or media tools.

A Web Worker gives intensive background processing a separate execution context. The page remains free to render, accept input and communicate progress while the worker performs calculations. This guide explains how to structure that split, move data efficiently and avoid creating a second bottleneck in the message channel.

Responsibility Main thread Dedicated Web Worker
User interaction Handles clicks, typing and focus Receives no DOM events
Rendering Paints controls and visual results Cannot access the DOM directly
CPU work Suitable for short, quick tasks Suitable for sustained computation
Data movement Sends requests and receives messages Copies or transfers data at message boundaries

Why Blocking the Main Thread Feels Slow

JavaScript runs on the browser’s main thread alongside rendering and input handling. A long synchronous function prevents the event loop from processing the next click, style update or animation frame. The result is not merely a delayed response; the page can appear frozen while the browser remains busy.

The effect is independent of connection speed. A customer on a fast NBN connection can still see a frozen interface if all processing happens locally, while a regional user on 4G or 5G can suffer an extra delay when the same page also transfers oversized payloads. Progressive web apps are a useful companion: the strategy in faster progressive web apps still depends on the main thread remaining available for navigation and feedback.

Australian teams should consider both national and local usage patterns. An operations console used in Sydney and Melbourne may handle bursts when offices open, while the same service must remain usable on phones outside major cities. Offloading eligible work can improve perceived speed across both groups, but it does not excuse inefficient data handling.

Separate Interface Work from Computation

A clean separation starts by assigning responsibilities. Keep DOM access, focus management, scrolling, form validation and visual state changes on the main thread. Give the worker computation or data transformation that does not need document, window or user-interface elements. The two sides then exchange small, explicit messages.

This boundary prevents accidental coupling. If a worker needs to display an error, it reports the error; the page decides how to present it. If the page needs updated progress, the worker sends a status object; the page schedules the visual update. Neither side should assume it can read or mutate the other’s variables, because ordinary objects sent through postMessage are cloned rather than shared.

Move a Real Task into a Worker

Start with a bounded operation whose output can be represented as transferable data. Create a module worker when the page loads, then send it a job only when needed:

const worker = new Worker("/workers/image-processor.js", {
  type: "module"
});

worker.postMessage(
  { id: "job-42", buffer, width, height },
  [buffer]
);

worker.onmessage = ({ data }) => {
  if (data.type === "progress") updateProgress(data);
  if (data.type === "complete") showResult(data);
};

The transfer list moves the ArrayBuffer instead of copying it, and the worker receives it through self.onmessage. A production worker should validate the payload, perform the operation, catch errors and send a structured completion message. It should never reach into the DOM or use a UI library.

Create the worker at an appropriate lifecycle point rather than for every item. Keeping one active worker can be enough for modest tasks, while a small pool can use multiple CPU cores for independent jobs. Always provide a fallback: browsers that do not support workers, a strict content security policy or a failed script load should run a smaller task on the main thread or explain that the feature is unavailable.

Build a Message-Based Job Pipeline

Long jobs benefit from a clear protocol. Give each request a unique identifier, describe its operation and data, and include options such as priority or cancellation. Return results with the same identifier so the page can reject stale messages after the user changes a filter or starts another job.

Control the queue rather than allowing unlimited work to accumulate. The main thread can keep a limited number of jobs in flight and send the next one after receiving a ready signal. Inside the worker, process items in chunks and yield between chunks if the operation supports asynchronous work. This keeps memory usage predictable and makes cancellation possible through worker.terminate().

Treat the worker as a queue consumer, not a place to recreate every application service. Database access, authentication decisions and authoritative business rules usually belong on the server. A local worker is best for calculations, parsing, filtering and transformations that can be repeated safely when a connection is slow or temporarily unavailable.

Transfer Data Without Copying Everything

Every message has a cost. Passing a large object with postMessage generally creates a structured clone, which can allocate substantial memory and delay the main thread. Prefer an ArrayBuffer, typed array or another transferable object for binary results, and include it in the transfer list so ownership moves without duplicating the bytes.

Shared memory is an option for advanced workloads, but it is not a shortcut around careful design. SharedArrayBuffer requires the page to be cross-origin isolated, normally through Cross-Origin-Opener-Policy: same-origin and Cross-Origin-Embedder-Policy: require-corp headers. Cross-origin resources may also need compatible CORS or Cross-Origin-Resource-Policy settings, which can affect third-party assets.

For repeated jobs, store durable input and intermediate results in IndexedDB instead of keeping everything in worker memory. This helps when a tab is closed, but IndexedDB is not a substitute for a server-side record of critical work. OffscreenCanvas can also move canvas rendering into a worker in supported browsers, although it adds complexity and should be justified by a measured rendering bottleneck.

Add Progress, Recovery, and Observability

A background task without feedback feels broken. Send periodic updates containing a job identifier, current phase, completed item count and an estimated total when one is known. Throttle these messages so a worker processing thousands of records cannot flood the main thread with updates of its own. For visual counters, coalesce state and paint from the page’s animation frame.

Design failure handling before deployment. Workers can be terminated by the browser, scripts can throw, and a user can cancel. Return a clear error type, keep retries idempotent and preserve enough state in IndexedDB to resume safely. The record-keeping approach in archiving social media pages illustrates why dated snapshots and source details are useful when a later process needs to verify what happened.

Do not confuse a Web Worker with a service worker. A service worker is designed for event-driven network and cache behaviour, including offline requests; it is not a dependable place for a long computation. Use the two separately when both are needed. Also avoid placing secret data in worker scripts or messages, since code delivered to the browser can be inspected by the user.

Prepare for Australian Users and Networks

Test on the devices and connections your customers actually use. A strong desktop on office NBN can hide worker overhead, while mid-range Android phones on regional 4G or 5G reveal memory pressure and transfer delays. Test a large Australian marketplace workload that calculates delivery options between Melbourne, Perth, Darwin and smaller regional centres; it is a useful way to combine representative geometry with realistic record counts.

Choose which work may run locally with a fallback to an Australian-hosted backend for authoritative jobs. Payment processing, permanent records and compliance-sensitive actions should not depend on a browser tab remaining open. Monitor job duration, message size, worker startup time and failure rate in the same way you monitor page-load metrics.

Practical safeguards keep the feature dependable across a geographically dispersed market:

With those safeguards, workers improve responsiveness without becoming the sole owner of critical data.