Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

iTechGuides is reader-supported. When you buy through links on our site, we may earn an affiliate commission. As an Amazon Associate I earn from qualifying purchases. Learn more

Angular web workers let you run CPU-intensive computation on a background thread so the main thread stays free to update the interface. Use one when a calculation is large enough to make the UI stutter. Adding a worker does not by itself make an app faster, because Angular’s guide publishes no speedup figure and no benchmark. The gain depends on your workload, so measure it before and after.

What a web worker does in an Angular app

Browsers run JavaScript on a single main thread, and that same thread handles rendering, click handling and change detection. A long calculation blocks all of those tasks until it finishes. Angular’s official guide on background processing says web workers move such computations into a separate thread, and it cites generating CAD drawings and heavy geometric calculations as examples of the kind of work that belongs there (Angular, “Background processing using web workers”).

A worker is worth considering when both of these are true:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
  • The computation takes long enough to be noticed, such as parsing a large file, running a simulation or processing thousands of records.
  • The user keeps interacting with the page while that work runs, so a frozen interface is a real problem.

If the work is short, or the page can wait for it, a worker adds code and a messaging layer without a visible benefit.

Generate the worker with the Angular CLI

In an existing Angular CLI project, run the generator with a location for the worker:

ng generate web-worker app

The CLI configures the project if the required setup is missing, then scaffolds a worker file and example usage code. The example’s import path ./app.worker refers to the generated app.worker.ts file. The CLI reference documents the command and its options (Angular CLI, “web-worker”).

The scaffolded code is a starting point. Its pattern is:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
if (typeof Worker !== 'undefined') {
  const worker = new Worker(new URL('./app.worker', import.meta.url));
  worker.onmessage = ({ data }) => {
    console.log(`page got message: ${data}`);
  };
  worker.postMessage('hello');
} else {
  // Web workers are not supported in this environment.
}

Replace the placeholder message with your real inputs, and replace the logging with code that updates component state. Also add error handling, since the scaffold does not show how to respond to failures.

Design the message boundary

The worker communicates only through messages. The main thread sends data with postMessage, and the worker responds through its own message handler, which can return results with postMessage. Worker code runs in a separate global context and cannot manipulate the DOM directly, so the main thread must do all rendering.

In practice, design the boundary around three questions:

  • What goes in? Send plain, serializable data such as numbers, arrays and objects. Pass only what the calculation needs, not whole component trees.
  • What comes out? Return the values the template needs, already in a shape ready to display.
  • What happens on failure? Decide how the UI reports a worker error and whether a pending request should be retried or cancelled.

Fallbacks for server rendering and unsupported environments

Not every environment can start a worker. Angular warns that some platforms, including @angular/platform-server used for server-side rendering, do not support web workers. Because the server cannot start one, code that depends on a worker will fail there unless you provide an alternative.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

The guard shown above handles this: when typeof Worker is undefined, run the same computation on the main thread instead. Keep the fallback correct, because it is the code path that runs during server rendering and in any browser without worker support. A fallback that returns different results from the worker path produces bugs that appear only in some environments.

Angular’s server-side and hybrid rendering guide adds that browser-specific APIs should run in the browser rather than on the server. It also describes browser-only render hooks as a way to limit that work to the client (Angular, “Server-side and hybrid rendering”).

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Compare the worker path with the main-thread path

Factor Web worker path Main-thread fallback
Where the computation runs Separate background thread Same thread as rendering and input
Effect on UI responsiveness during long work Main thread stays free for UI updates Interface can freeze until the work completes
Environment support Requires Worker to exist; not supported under @angular/platform-server Runs anywhere the application code runs
Data transfer Inputs and outputs cross a message boundary Direct function calls and shared memory
Code complexity Worker file, message handling, error handling Single code path
Published speedup or threshold Not stated by Angular’s guide Not stated by Angular’s guide

Build-system limits to plan for

Angular’s new build system supports the same worker instantiation syntax used with the browser builder, so the new Worker(new URL(...), import.meta.url) pattern carries over. Angular’s migration guide lists two limitations that affect how you organize and validate worker code (Angular, “Migrating to new build system”):

  • Worker code is not currently type-checked by the TypeScript compiler. Write unit tests for worker logic, and do not rely on the compiler to catch type errors inside the worker file.
  • Nested workers are not processed by the build system. Do not design a worker that starts another worker.

A practical checklist before you ship

  • Confirm the computation is slow enough to affect the interface, using a browser profiler on the existing code path.
  • Generate the worker with ng generate web-worker and replace the scaffold inputs with real data.
  • Keep the message payloads small and serializable.
  • Guard every new Worker call with typeof Worker !== 'undefined'.
  • Test the fallback path, including server rendering.
  • Measure the result on the same workload and device before keeping the worker.

Angular web workers are a good fit for isolated, CPU-heavy work whose results can be sent back as plain data. They add a messaging layer, a fallback path and some build-system constraints, so they are worth the cost only when the main thread is actually the bottleneck.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.