0
0
Angularframework~5 mins

Web workers for heavy computation in Angular

Choose your learning style9 modes available
Introduction

Web workers let your app do heavy work without freezing the screen. They run tasks in the background so users can keep clicking and typing smoothly.

When you need to process large data sets without slowing down the app interface.
When performing complex calculations that take noticeable time.
When you want to keep animations and user interactions smooth during heavy tasks.
When fetching and processing data from APIs that require extra work before showing.
When you want to offload tasks like image or video processing from the main thread.
Syntax
Angular
ng generate web-worker worker-name

// In your component or service:
const worker = new Worker(new URL('./worker-name.worker.ts', import.meta.url));
worker.postMessage(data);
worker.onmessage = ({ data }) => {
  console.log('Result from worker:', data);
};

Use Angular CLI to generate a web worker file with ng generate web-worker.

Web workers communicate with the main app using postMessage and onmessage.

Examples
This command creates a new web worker file named heavyCalc.worker.ts.
Angular
ng generate web-worker heavyCalc
This code sends a number to the worker and logs the result when the worker sends it back.
Angular
const worker = new Worker(new URL('./heavyCalc.worker.ts', import.meta.url));
worker.postMessage(1000000);
worker.onmessage = ({ data }) => {
  console.log('Sum is', data);
};
The worker listens for messages, does the sum calculation, then sends the result back.
Angular
// heavyCalc.worker.ts
addEventListener('message', ({ data }) => {
  let sum = 0;
  for(let i = 0; i <= data; i++) {
    sum += i;
  }
  postMessage(sum);
});
Sample Program

This Angular component uses a web worker to calculate the sum of numbers from 0 to 1,000,000. When you click the button, the calculation runs in the background. The UI stays responsive, and the result shows when ready.

Angular
import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  template: `
    <h1>Sum Calculator with Web Worker</h1>
    <button (click)="startCalculation()">Calculate Sum</button>
    <p *ngIf="result !== null">Result: {{ result }}</p>
  `
})
export class AppComponent {
  result: number | null = null;
  worker: Worker | undefined;

  constructor() {
    if (typeof Worker !== 'undefined') {
      this.worker = new Worker(new URL('./sum.worker.ts', import.meta.url));
      this.worker.onmessage = ({ data }) => {
        this.result = data;
      };
    }
  }

  startCalculation() {
    this.result = null;
    this.worker?.postMessage(1000000);
  }
}

// sum.worker.ts
addEventListener('message', ({ data }) => {
  let sum = 0;
  for (let i = 0; i <= data; i++) {
    sum += i;
  }
  postMessage(sum);
});
OutputSuccess
Important Notes

Web workers cannot access the DOM directly. They only communicate via messages.

Always check if Worker is supported in the browser before creating one.

Keep the worker code simple and focused on heavy tasks to get the best performance.

Summary

Web workers run heavy tasks in the background to keep the app smooth.

Use Angular CLI to create workers easily and communicate with them using messages.

They help improve user experience by preventing UI freezes during big computations.