Angular Performance Optimization: Best Practices for Core Web Vitals

As web performance becomes increasingly critical, Angular developers must ensure their applications align with Core Web Vitals—Google’s metrics that measure a website’s speed, responsiveness, and visual stability. Focusing on these metrics helps improve user experience and boost search rankings. This blog highlights the best practices for Angular developers, complete with actionable examples.

What are Core Web Vitals?

Core Web Vitals are a set of performance metrics introduced by Google to measure key aspects of the user experience. These metrics focus on loading performance, interactivity, and visual stability. Let’s break them down:

  • Largest Contentful Paint (LCP): This measure measures how fast a web page’s most visible and important element (like a banner image or heading) appears. A fast LCP ensures users can quickly see meaningful content. The target is under 2.5 seconds.
  • First Input Delay (FID): Measures the time between when a user interacts with the page (like clicking a button) and when the browser responds. A low FID ensures the page feels responsive. The target is less than 100 milliseconds.
  • Cumulative Layout Shift (CLS): Measures how much visible content moves around unexpectedly while the page is loading. Reducing CLS ensures the app feels stable and avoids frustrating layout shifts. The target is below 0.1.

1. Optimize Lazy Loading for Faster LCP

Lazy loading of modules and assets ensures that only critical resources are loaded initially, improving LCP.

Implementation Example:

  • In the AppRoutingModule, configure lazy loading for feature modules:
const routes: Routes = [
{ path: '', component: HomeComponent },
{ path: 'dashboard', loadChildren: () => import('./dashboard/dashboard.module').then(m => m.DashboardModule) },
];
@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule {}
  • Ensure images are lazy-loaded using Angular’s built-in directive:
<img [src]="imagePath" loading="lazy" alt="Lazy loaded image" />

2. Preload Key Resources

While lazy loading is essential, preloading critical assets ensures smooth transitions.

  • Use Angular’s PreloadAllModules strategy:
imports: [
  RouterModule.forRoot(routes, { preloadingStrategy: PreloadAllModules })
]

3. Minimize JavaScript Bundle Size

Large JavaScript bundles increase load times, negatively impacting LCP.

Best Practices:

  • Enable tree-shaking to remove unused code.
  • Use Angular CLI’s production build.
ng build --prod
  • Split code with @angular/compiler-cli tools like Webpack.

4. Improve Interactivity for FID

Use Web Workers to offload heavy computations from the main thread, reducing input delay.

Implementation Example:

Create a Web Worker for CPU-intensive tasks:

1. Generate a Worker

ng generate web-worker app

2. Delegate Heavy Computations

// Inside app.worker.ts
addEventListener('message', ({ data }) => {
  const result = performHeavyTask(data);
  postMessage(result);
});

3. Use the Worker in Your Component

const worker = new Worker(new URL('./app.worker', import.meta.url));
worker.postMessage(data);
worker.onmessage = ({ data }) => {
  this.result = data;
};

Enhance Your App's Speed and Stability with Our Angular Development Services

5. Ensure Visual Stability for CLS

  • Prevent layout shifts by defining dimensions for images and reserving space for dynamic content.
<img [src]="imagePath" [width]="300" [height]="200" alt="Image with defined dimensions" />
<!-- Reserve space for ads or dynamic content -->
<div class="ad-slot" style="width:300px; height:250px;"></div>
  • Use ngx-skeleton-loader to display placeholders while content loads:
<ngx-skeleton-loader count="1" [theme]="{ width: '100%', height: '200px' }"></ngx-skeleton-loader>

6. Monitor Performance with Angular Universal

Server-side rendering (SSR) improves performance by pre-rendering HTML on the server.

Related read: Angular Performance Boost: Unlocking SSR with Cloud Functions

1. Add Angular Universal

ng add @nguniversal/express-engine

2. Build and Serve Your App

npm run build:ssr && npm run serve:ssr

7. Leverage Performance Monitoring Tools

  • Use Lighthouse to audit Core Web Vitals.
  • Integrate Google Analytics or Web Vitals library for real-time monitoring.

Example:

Install the Web Vitals library:

npm install web-vitals

Capture metrics in your app:

import { getCLS, getFID, getLCP } from 'web-vitals'; 
getCLS(console.log); 
getFID(console.log); 
getLCP(console.log);
coma

Conclusion

Optimizing Angular applications for Core Web Vitals is crucial for delivering a fast and seamless user experience. By implementing lazy loading, using Web Workers, ensuring visual stability, and leveraging server-side rendering, you can significantly enhance your app’s performance.

Keep Reading

Keep Reading

Master Epic Integration with SMART on FHIR in Just 60 Minutes

Register Here
  • Service
  • Career
  • Let's create something together!

  • We’re looking for the best. Are you in?