LearnAI ToolsCareerPractice BuildsPlayContact
Lesson 3214 min read

Lazy Loading

Split your application's JavaScript by route, so each route's code downloads only when it's actually visited.

Why Lazy Load

Without lazy loading, every route's component code ships in one large initial bundle, downloaded before the app can even show its first page. Lazy loading splits that bundle by route, so a visitor only downloads the code for pages they actually visit.

Lazy-Loading a Standalone Component

loadComponent replaces a direct component import with a dynamic import() — Angular's build tooling automatically splits that component into its own separate chunk.

export const routes: Routes = [
{ path: '', component: HomeComponent }, // loaded eagerly, in the main bundle
{
path: 'settings',
loadComponent: () => import('./settings/settings.component').then(m => m.SettingsComponent),
},
];

Lazy-Loading a Group of Routes

loadChildren lazily loads an entire set of related routes at once — useful for a whole feature area (like an admin section) that a typical visitor may never open.

// app.routes.ts
export const routes: Routes = [
{
path: 'admin',
loadChildren: () => import('./admin/admin.routes').then(m => m.ADMIN_ROUTES),
},
];
// admin/admin.routes.ts
export const ADMIN_ROUTES: Routes = [
{ path: '', component: AdminDashboardComponent },
{ path: 'users', component: AdminUsersComponent },
];

Preloading Strategies

To balance a small initial bundle with fast subsequent navigation, Angular can preload lazy routes' code in the background after the app loads, rather than waiting until the visitor actually clicks.

// app.config.ts
import { provideRouter, withPreloading, PreloadAllModules } from '@angular/router';
export const appConfig: ApplicationConfig = {
providers: [provideRouter(routes, withPreloading(PreloadAllModules))],
};
The Best of Both Worlds

PreloadAllModules keeps the true initial bundle small (fast first load), while quietly fetching every other route's code shortly after — so by the time a visitor clicks a link, that route's code is often already cached.

FAQs

Yes — canActivate, canMatch, and other guards apply exactly the same way, whether a route is eagerly or lazily loaded.

It provides the most dramatic benefit on large apps, but even a medium-sized app with a rarely-visited admin section benefits from keeping that code out of the initial bundle.

Summary

loadComponent and loadChildren split your app's JavaScript by route, and a preloading strategy can fetch that code in the background for fast subsequent navigation. With routing covered, the next section moves into forms.

Next Lesson →

Template-Driven Forms