0
0
Angularframework~8 mins

Web workers for heavy computation in Angular - Performance & Optimization

Choose your learning style9 modes available
Performance: Web workers for heavy computation
HIGH IMPACT
This concept affects the page's input responsiveness and smoothness by offloading heavy tasks from the main thread.
Performing heavy computation without blocking the UI
Angular
const worker = new Worker(new URL('./heavy.worker.ts', import.meta.url));
worker.postMessage('start');
worker.onmessage = ({ data }) => {
  console.log('Result:', data);
};
Moves heavy computation to a separate thread, keeping the main thread free for UI tasks.
📈 Performance GainMain thread remains responsive; INP improves significantly; no UI jank.
Performing heavy computation without blocking the UI
Angular
function heavyCalculation() {
  let result = 0;
  for (let i = 0; i < 1e9; i++) {
    result += i;
  }
  return result;
}

heavyCalculation();
This runs heavy computation on the main thread, blocking UI updates and user interactions.
📉 Performance CostBlocks main thread for hundreds of milliseconds, causing poor INP and janky UI.
Performance Comparison
PatternDOM OperationsReflowsPaint CostVerdict
Heavy computation on main threadN/ABlocks reflows during computationDelays paint and composite[X] Bad
Heavy computation in web workerN/ANo blocking of reflowsPaint and composite proceed smoothly[OK] Good
Rendering Pipeline
Heavy computation on the main thread delays the rendering pipeline by blocking the event loop. Using web workers offloads this work, allowing the main thread to continue style calculation, layout, paint, and composite without delay.
Event Handling
Style Calculation
Layout
Paint
Composite
⚠️ BottleneckMain thread blocking during heavy computation
Core Web Vital Affected
INP
This concept affects the page's input responsiveness and smoothness by offloading heavy tasks from the main thread.
Optimization Tips
1Always run heavy computations in web workers to keep the UI responsive.
2Avoid blocking the main thread with synchronous loops or calculations.
3Use Angular's built-in support for web workers to simplify integration.
Performance Quiz - 3 Questions
Test your performance knowledge
What is the main performance benefit of using web workers for heavy computation in Angular?
AKeeps the main thread free to handle UI updates and user input
BReduces the total CPU usage of the page
CDecreases the bundle size of the application
DImproves the initial page load time by lazy loading scripts
DevTools: Performance
How to check: Record a performance profile while triggering the heavy computation. Look for long tasks blocking the main thread.
What to look for: Long tasks (red bars) on the main thread indicate blocking; absence means good use of web workers.