DEV Community

Cover image for ๐Ÿš€ Web Workers in Angular: Boost App Performance by Offloading Heavy Tasks
ROHIT SINGH
ROHIT SINGH

Posted on

๐Ÿš€ Web Workers in Angular: Boost App Performance by Offloading Heavy Tasks

When we build Angular applications, performance is one of the top priorities. No user likes a frozen screen or unresponsive UI, especially in data-heavy applications. But when you perform CPU-intensive tasksโ€”like parsing a huge JSON, encrypting data, or running mathematical calculationsโ€”the main thread gets blocked.

This leads to:
โŒ Janky scrolling
โŒ Slow clicks
โŒ A poor overall experience

So how do we solve this?

Enter Web Workers.

In this blog, weโ€™ll explore:

What Web Workers are

Why theyโ€™re important in Angular apps

Step-by-step implementation in Angular

Real-world examples

Limitations & best practices

๐Ÿ”น What Are Web Workers?

Think of Web Workers as background assistants.
They run JavaScript code in a separate thread, leaving the main UI thread free to handle rendering, animations, and user interactions.

In simple terms:

The main thread is your Angular app UI.

A Web Worker is a helper that does heavy lifting in the background.

๐Ÿ“Œ Example: Imagine youโ€™re cooking and also talking with a guest. If you try to do everything yourself, youโ€™ll be slow and distracted. Instead, if you hire an assistant to chop vegetables (background work), you can focus on the conversation (UI).

๐Ÿ”น Why Use Web Workers in Angular?

Here are some clear benefits of using workers in your Angular projects:

Benefit Impact on Angular App
Non-blocking UI Keeps the app smooth
Parallel Processing Utilizes multiple CPU cores
Better UX No frozen screens
Scalable Performance Handles large datasets without lag

Typical use cases in Angular:

๐Ÿ”„ Processing large arrays or JSON files

๐Ÿ” Data encryption/decryption

๐Ÿ–ผ๏ธ Image compression or resizing

๐Ÿ“Š Complex financial or statistical calculations

๐Ÿ”น Setting Up Web Workers in Angular

Angular CLI makes adding Web Workers simple.

โœ… Step 1: Generate a Web Worker

Run:

ng generate web-worker app
Enter fullscreen mode Exit fullscreen mode

This will:

Create src/app/app.worker.ts

Update angular.json with worker support

โœ… Step 2: Write Worker Logic

Inside app.worker.ts:

/// <reference lib="webworker" />

addEventListener('message', ({ data }) => {
  // Example: Heavy calculation
  let result = 0;
  for (let i = 0; i < data; i++) {
    result += i;
  }
  postMessage(result); // Send back result
});
Enter fullscreen mode Exit fullscreen mode

โœ… Step 3: Call Worker from Component

In app.component.ts:

export class AppComponent {
  result!: number;

  calculateHeavyTask() {
    if (typeof Worker !== 'undefined') {
      const worker = new Worker(new URL('./app.worker', import.meta.url));

      worker.onmessage = ({ data }) => {
        this.result = data;
        console.log('Result from worker:', data);
      };

      worker.postMessage(1000000000); // Send data to worker
    } else {
      console.log('Web Workers not supported.');
    }
  }
}

Enter fullscreen mode Exit fullscreen mode

Now, instead of freezing the UI for seconds, the calculation runs in the background.

๐Ÿ”น Example: With vs Without Web Worker
โŒ Without Worker (UI freezes)

let result = 0;
for (let i = 0; i < 1000000000; i++) {
  result += i;
}
console.log(result);

Enter fullscreen mode Exit fullscreen mode

The user canโ€™t click buttons or scroll until this finishes.

โœ… With Worker (UI stays responsive)

worker.postMessage(1000000000);
Enter fullscreen mode Exit fullscreen mode

The UI remains smooth while the worker processes the task.

๐Ÿ”น Real-World Angular Use Cases

Data-Heavy Dashboards โ€“ Large datasets (e.g., stock market apps) processed in workers while UI shows charts.

Image Uploads โ€“ Compress or resize images in workers before uploading, improving performance.

Cryptography Apps โ€“ Encrypt/decrypt data in workers for better security without blocking the UI.

Machine Learning Models โ€“ Run ML predictions in workers without slowing down UI animations.

๐Ÿ”น Limitations of Web Workers

Before you add workers everywhere, note these drawbacks:

โŒ No direct access to the DOM (document, window)

โŒ Debugging is harder than normal code

โŒ Communication between worker and main thread adds overhead

โŒ Not ideal for tiny tasks (use only for CPU-heavy logic)

๐Ÿ”น Best Practices

โœ” Use workers for long-running tasks (more than 50ms)
โœ” Limit the number of workers (too many = memory overhead)
โœ” Consider RxJS + Web Workers for reactive data pipelines
โœ” Always handle worker termination when not in use

๐Ÿ”น Conclusion

Web Workers in Angular are a powerful way to keep your apps responsive.
By offloading heavy computations to a background thread, you:

Improve user experience

Ensure smooth UI interactions

Unlock the true potential of modern CPUs

Next time your Angular app feels sluggish with big data or calculations, donโ€™t block the main threadโ€”use a Web Worker.

๐Ÿ‘‰ Try it in your project today and see the difference!

โœ… If you found this useful, share it with your Angular developer friends!

๐Ÿš€ Rohit Singh ๐Ÿš€ โ€“ Medium

Read writing from ๐Ÿš€ Rohit Singh ๐Ÿš€ on Medium. Full-stack developer with 6+ years in Angular, Node.js & AWS. Sharing tips, best practices & real-world lessons from building scalable apps.

favicon medium.com

Top comments (0)