🅰️ Angular Intermediate

What is Angular lazy loading and preloading strategy?

Answer

Lazy loading splits the application into multiple JavaScript bundles and loads them on-demand when the user navigates to specific routes. Implementation: use loadChildren (for modules) or loadComponent (for standalone components): { path: "admin", loadChildren: () => import("./admin/admin.module").then(m => m.AdminModule) }. The build produces separate chunk files. Preloading strategies determine which lazy modules are pre-downloaded after initial load: (1) NoPreloading (default): modules load only when navigated. First visit to /admin has a loading delay; (2) PreloadAllModules: after initial app loads, background-download all lazy modules. Good if the app isn't too large: RouterModule.forRoot(routes, { preloadingStrategy: PreloadAllModules }). First navigation to /admin is instant; (3) Custom PreloadingStrategy: selectively preload based on route data or other conditions. Implement PreloadingStrategy interface: only preload routes with data: { preload: true }. Good for large apps where PreloadAllModules wastes bandwidth; (4) QuicklinkStrategy: preload links visible in the current viewport (IntersectionObserver) — preloads what the user is likely to click next. Third-party library ngx-quicklink. Bundle analysis: ng build --stats-json then npx webpack-bundle-analyzer dist/stats.json to visualize chunk sizes. Aim for: initial bundle <200KB gzipped, lazy chunks proportional to feature complexity.