Performance: Lazy loading standalone components
This affects the initial page load speed by deferring loading of components until needed, improving time to interactive.
Jump into concepts and practice - no test required
const featureLoader = () => import('./feature.component').then(m => m.FeatureComponent); @Component({ selector: 'app-root', template: '<ng-container *ngComponentOutlet="featureLoader()"></ng-container>' }) export class AppComponent {}
import { FeatureComponent } from './feature.component'; @Component({ selector: 'app-root', template: '<app-feature></app-feature>' }) export class AppComponent {}
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Eager loading standalone component | High upfront DOM nodes | Multiple reflows during initial load | High paint cost due to large bundle | [X] Bad |
| Lazy loading standalone component | DOM nodes added on demand | Single reflow when component loads | Lower paint cost initially | [OK] Good |
loadComponent to lazy load standalone components in routes.loadComponent with dynamic import and then returns the component class, which is correct.{ path: 'dashboard', loadComponent: () => import('./dashboard.component').then(m => m.DashboardComponent) }loadComponent with dynamic import delays loading the component until the route is accessed.{ path: 'profile', loadComponent: import('./profile.component').then(m => m.ProfileComponent) }loadComponent property must be a function returning a Promise, so it needs an arrow function wrapping the import.AdminComponent and UserComponent, under routes '/admin' and '/user'. Which is the best way to configure the routes to optimize initial load time?loadComponent with dynamic imports allows each component to load only when its route is visited, reducing initial load.loadComponent with dynamic imports for both routes separately loads each component lazily and separately, optimizing load time better than eager loading or bundling.