Skip to content
Tutorials Center
My learning

Topics

Lesson 52 of 74 ยท Quality and Performance

Web Workers in Angular

Keep your Angular UI smooth by moving heavy computation into a Web Worker. Learn ng generate web-worker, message passing, signals integration and when not to use one, with runnable stand-ins.

JavaScript in the browser runs on a single main thread. That thread draws the page, handles clicks and runs Angular's change detection. If you ask it to sort a million rows or parse a 20 MB file, it cannot do anything else until the work is done: animations freeze, buttons do not respond, and the browser may offer to kill the page.

A Web Worker is a script that runs on a separate thread. It cannot touch the DOM, but it can crunch numbers while the main thread keeps the UI alive. Angular's CLI can set one up for you. This lesson shows how, how to talk to a worker from a service with signals, and how to decide whether a worker is the right fix. Slowness has other causes too; see Performance Tuning first.

Real versus stand-in. Our example sandbox cannot start Angular or a browser Worker from the TypeScript runner, so the bash and typescript blocks showing the CLI output and Angular code are read-only. The runnable examples use Node's worker_threads, which has the same message-passing model, to show the real behavior: heavy work in a separate thread while the main thread stays responsive. In the browser you use new Worker(...) and postMessage; the ideas carry over unchanged.

What a worker is, and what it is not

flowchart LR
  M["Main thread<br/>UI, Angular, DOM"] -- "postMessage(data)" --> W["Worker thread<br/>pure computation"]
  W -- "postMessage(result)" --> M

The two threads share no variables. They send copies of data as messages.

  • A worker has no DOM, no document, no window, and cannot use Angular components or most services. It can use fetch, timers, IndexedDB and your plain TypeScript functions.
  • Messages are copied (structured clone). Big arrays are copied too, unless you transfer them (see below).
  • Starting a worker costs a few milliseconds and some memory. It pays off for work that takes longer than roughly 50 ms, which is about the point where users start to feel the lag.

Good fits: image or audio processing, parsing and filtering big datasets, search indexing, compression, cryptographic hashing, heavy math. Poor fits: anything that needs the DOM, tiny tasks, or slow network calls (the browser already does those without blocking).

Generating a worker with the CLI

Terminal
ng generate web-worker app

The CLI creates a worker file next to your code, adds a TypeScript config for it and updates the project settings:

TEXT
CREATE src/app/app.worker.ts
CREATE tsconfig.worker.json
UPDATE tsconfig.app.json
UPDATE angular.json

The generated worker is a few lines that listen for messages:

TypeScript
// src/app/app.worker.ts
/// <reference lib="webworker" />

addEventListener('message', ({ data }) => {
  const response = `worker response to ${data}`;
  postMessage(response);
});

The first line tells TypeScript to use the worker's global types (addEventListener and postMessage belong to the worker scope there, not the window). Replace the body with real work. A prime-counting job is a classic stand-in for "slow":

TypeScript
// src/app/primes.worker.ts
/// <reference lib="webworker" />

export interface PrimeRequest { id: number; limit: number }
export interface PrimeResponse { id: number; count: number; ms: number }

function countPrimes(limit: number): number {
  const sieve = new Uint8Array(limit + 1);
  let count = 0;
  for (let i = 2; i <= limit; i++) {
    if (sieve[i] === 0) {
      count++;
      for (let j = i * 2; j <= limit; j += i) sieve[j] = 1;
    }
  }
  return count;
}

addEventListener('message', ({ data }: MessageEvent<PrimeRequest>) => {
  const start = performance.now();
  const count = countPrimes(data.limit);
  postMessage({ id: data.id, count, ms: Math.round(performance.now() - start) } satisfies PrimeResponse);
});

The id lets the main thread match each answer to its question, which matters as soon as two requests are in flight.

Calling the worker from a service

Keep the Worker object inside a service, so components do not know about threads. The service exposes signals:

TypeScript
// prime.service.ts
import { Injectable, OnDestroy, signal } from '@angular/core';
import type { PrimeRequest, PrimeResponse } from './primes.worker';

@Injectable({ providedIn: 'root' })
export class PrimeService implements OnDestroy {
  readonly result = signal<PrimeResponse | null>(null);
  readonly busy = signal(false);
  readonly supported = typeof Worker !== 'undefined';

  private worker?: Worker;
  private latestId = 0;

  count(limit: number): void {
    if (!this.supported) {
      return; // for example during server-side rendering: fall back or do nothing
    }
    this.worker ??= this.createWorker();
    this.busy.set(true);
    const request: PrimeRequest = { id: ++this.latestId, limit };
    this.worker.postMessage(request);
  }

  private createWorker(): Worker {
    const worker = new Worker(new URL('./primes.worker', import.meta.url), { type: 'module' });
    worker.onmessage = ({ data }: MessageEvent<PrimeResponse>) => {
      if (data.id !== this.latestId) return; // an older request: ignore it
      this.result.set(data);
      this.busy.set(false);
    };
    worker.onerror = () => this.busy.set(false);
    return worker;
  }

  ngOnDestroy(): void {
    this.worker?.terminate();
  }
}

Several details are worth studying.

  • new Worker(new URL('./primes.worker', import.meta.url)) is the pattern the build tool recognizes, so it can bundle the worker as a separate file. Do not build the path from a variable.
  • typeof Worker !== 'undefined' guards against server-side rendering, where there is no Worker (SSR, Hydration and Prerendering).
  • Responses with an old id are ignored, so a slow answer never overwrites a newer one.
  • terminate() stops the thread when the service is destroyed. A forgotten worker keeps running.
  • Messages arrive outside Angular's usual triggers, but because we write to signals, the template updates correctly, also without Zone.js (Signals: signal, computed and effect).

A component then just reads the signals:

TypeScript
@Component({
  selector: 'app-primes',
  template: `
    <button type="button" (click)="primes.count(5_000_000)" [disabled]="primes.busy()">Count primes</button>
    @if (primes.busy()) { <p>Working...</p> }
    @if (primes.result(); as r) { <p>{{ r.count }} primes (computed in {{ r.ms }} ms)</p> }
  `,
})
export class PrimesComponent {
  protected readonly primes = inject(PrimeService);
}

See it work: blocked versus free

The first stand-in shows the problem. A heartbeat timer ticks every 50 ms, like the UI staying alive. We run the same heavy function once on the main thread and once in a worker thread, and count heartbeats.

TypeScript Main thread blocked versus worker thread free

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

The main-thread run produces almost no ticks, because nothing else can run until the loop ends. With a worker the timer keeps firing. This is exactly what "the UI stays responsive" means.

Messages, ids and cancellation

The second stand-in re-creates the service logic: request ids, ignoring stale answers and terminating. It uses a worker thread that sleeps in proportion to the limit, so a later request can finish before an earlier one.

TypeScript Ignoring stale answers with request ids

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

Transferring big data

By default postMessage copies the data. For a large ArrayBuffer (an image, audio samples) copying wastes time and memory. You can transfer ownership instead: the buffer moves to the other thread for free, and the sender can no longer use it.

TypeScript
const pixels = new Uint8ClampedArray(4_000_000);
worker.postMessage({ pixels }, [pixels.buffer]); // moved, not copied
console.log(pixels.length); // 0: this thread gave up the buffer

Using a worker without a lot of ceremony

For simple cases you may not need the CLI at all. Any function can be moved to a worker by hand, as in the earlier example, and libraries such as Comlink wrap postMessage so that calling a worker looks like calling an async function. Keep the worker file free of Angular imports: it should contain plain TypeScript and nothing else, so it stays small and testable (you can unit test countPrimes without any worker at all).

When not to use a worker

  • The work is not the bottleneck. Slow rendering from too many bindings needs OnPush, signals and @for with track, not threads (Change Detection).
  • The data is huge and constantly shared. Copying costs more than the computation.
  • You need the DOM. Workers cannot touch it.
  • The task is small. The cost of messaging exceeds the saving.

Measure first (the browser's Performance panel shows "long tasks" over 50 ms), then move only the heavy function.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why can a Web Worker keep the UI responsive?

    A worker does not make code faster. It moves the work off the main thread so the UI is not blocked while it runs.
  2. 2. Which of these can code inside a worker NOT do?

    Workers have no document or window, so they cannot touch the DOM. They exchange messages with the main thread instead.
  3. 3. Why does the example service attach an id to every request?

    Answers can arrive in a different order than the requests. Comparing the id with the latest one prevents stale data from overwriting newer data.
  4. 4. What does transferring an ArrayBuffer in postMessage do?

    Transfer avoids the copy of large data. The sending thread can no longer use the buffer afterwards.

Summary

  • The main thread runs the UI and Angular; long synchronous work freezes it.
  • A Web Worker runs on another thread, has no DOM and talks through postMessage.
  • ng generate web-worker sets up the worker file and build configuration; create the worker with new Worker(new URL('./x.worker', import.meta.url), { type: 'module' }).
  • Wrap the worker in a service that exposes signals, uses request ids to drop stale answers, checks typeof Worker for SSR and terminates on destroy.
  • Transfer large buffers instead of copying them.
  • Measure before you move code to a worker; many slow pages need better change detection, not a new thread.
  • The Angular code is real and read-only; the runnable examples use Node's worker_threads, which shares the model but is not the browser API.

Next: Internationalization