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.
Web workers for heavy computation in 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.
heavyCalc.worker.ts.ng generate web-worker heavyCalc
const worker = new Worker(new URL('./heavyCalc.worker.ts', import.meta.url)); worker.postMessage(1000000); worker.onmessage = ({ data }) => { console.log('Sum is', data); };
// heavyCalc.worker.ts addEventListener('message', ({ data }) => { let sum = 0; for(let i = 0; i <= data; i++) { sum += i; } postMessage(sum); });
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.
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); });
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.
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.