tezvyn:

Angular Lazy Loading: Ship Less Code Upfront

AI-drafted, machine-checkedSource: v18.angular.devintermediate
Angular Lazy Loading: Ship Less Code Upfront

Think of your app as an encyclopedia. Lazy loading only fetches the volume (feature module) you need, when you need it, instead of loading the whole set upfront. Use it for distinct sections like dashboards.

WHY IT EXISTS: By default, Single-Page Applications (SPAs) bundle all their code into a single large file. As an app grows, this initial download becomes a bottleneck, leading to slow load times and a poor user experience. Lazy loading was created to solve this by splitting the application into smaller chunks that are loaded only when needed.

THE MENTAL MODEL: An Angular app is like a multi-volume encyclopedia. By default, Angular makes you carry all 26 volumes (the entire app bundle) just to look up one entry. Lazy loading lets you start with just the index and cover (the core app), and you only grab Volume 'S' (the Settings module) when the user navigates to the settings page. This dramatically reduces the initial weight and load time.

HOW IT WORKS: You organize related components, directives, and pipes into a distinct feature module. Then, in your main routing configuration, instead of directly importing a component for a route, you use the loadChildren property. This property uses a dynamic import() function to point to the module's file path. When a user navigates to that route, the Angular router fetches the required JavaScript chunk from the server, integrates it into the application, and then renders the view.

WHEN TO USE IT: Apply lazy loading to any feature area that isn't required for the initial, visible part of your application. Prime candidates include user profiles, settings pages, admin dashboards, and any complex workflow that lives behind a user click. If a user has to navigate to get there, it can probably be lazy-loaded.

WHEN NOT TO USE IT: Avoid lazy loading core, universally needed parts of the application shell, such as the main navigation bar, footer, or essential services. For very small applications with only a few pages, the complexity of setting up lazy loading may outweigh the performance benefits.

ONE CANONICAL EXAMPLE: In an e-commerce app, the main routes for browsing products are loaded eagerly. The admin section, however, is lazy-loaded. The route configuration would look like this: { path: 'admin', loadChildren: () => import('./admin/admin.module').then(m => m.AdminModule) }. A regular customer never downloads the code for the admin panel, but when an administrator navigates to /admin, Angular fetches and loads the AdminModule on demand.

Read the original → v18.angular.dev

Get five bites like this every day.

Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.