December 28, 2024
Performance remains a cornerstone of excellent Angular applications. In 2024, Angular continues evolving with new tools and techniques—especially lazy loading enhancements, server-side rendering (SSR) improvements, and the experimental Signals API—that help reduce your app’s Time To Interactive (TTI) and boost Lighthouse scores.
Let’s explore these modern strategies with practical examples.
1. Optimizing Lazy Loading
Lazy loading splits your app into chunks loaded only when needed, cutting initial bundle size.
Angular 17 Lazy Loading Improvements
Angular 17 introduced better chunking and deferred loading for routes and components, making lazy loading even more efficient.
Example: Lazy loading a feature module
// app-routing.module.ts
const routes: Routes = [
{
path: 'dashboard',
loadChildren: () =>
import('./dashboard/dashboard.module').then(m => m.DashboardModule),
},
];
With Angular 17+, lazy loaded chunks are smaller and loaded faster thanks to enhanced dependency analysis.
2. Leveraging Angular SSR and Hydration
Angular Universal enables SSR to pre-render pages on the server, improving perceived speed and SEO. Angular 17 adds improved hydration—meaning the client can pick up server-rendered HTML seamlessly.
Example: Basic SSR setup
Install Angular Universal schematics:
ng add @nguniversal/express-engine
Build and serve:
npm run build:ssr
npm run serve:ssr
Hydration usage:
Angular 17 automatically supports hydration with minimal config, ensuring faster interactivity without a full re-render.
3. Signals: Next-Gen Reactivity for Performance
Signals are Angular’s experimental reactive primitives that track state changes more granularly than RxJS observables.
Using signals reduces unnecessary change detection cycles, boosting performance especially in large UIs.
Example: Using a signal
import { Component, signal } from '@angular/core';
@Component({
selector: 'app-counter',
template: `
<button (click)="increment()">Increment</button>
<p>Count: {{ count() }}</p>
`,
})
export class CounterComponent {
count = signal(0);
increment() {
this.count.set(this.count() + 1);
}
}
Signals automatically trigger fine-grained updates, minimizing expensive change detection runs.
4. Other Tips for Reducing TTI
- Image optimization: Use
<img loading="lazy">
and responsive images. - Preloading strategies: Customize route preloading to load critical chunks early but delay others.
- Avoid heavy initialization in
ngOnInit
: Defer expensive logic usingsetTimeout
or observables. - Track bundle size: Use
source-map-explorer
to analyze and trim dependencies.
Summary
By combining Angular 17’s lazy loading improvements, SSR with hydration, and the power of signals, you can drastically improve your Angular app’s startup speed, responsiveness, and Lighthouse metrics in 2024.
Would you like a code sandbox demo or configuration templates for these optimizations?