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
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
});
โ 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.');
}
}
}
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);
The user canโt click buttons or scroll until this finishes.
โ
With Worker (UI stays responsive)
worker.postMessage(1000000000);
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!
Top comments (0)