Angular course Β· Module 3: Modules
Lazy Loading - On-Demand Squads
In this lesson3
Lazy loading is a technique for loading modules only when they are needed - like dispatching squads only when the need arises.
Lazy Loading Configuration
// app-routing.module.ts
const routes: Routes = [
{ path: '', redirectTo: '/home', pathMatch: 'full' },
{ path: 'home', component: HomeComponent },
// Lazy loaded modules
{
path: 'samurai',
loadChildren: () => import('./features/samurai/samurai.module')
.then(m => m.SamuraiModule)
},
{
path: 'dojo',
loadChildren: () => import('./features/dojo/dojo.module')
.then(m => m.DojoModule)
}
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }Routing in a Feature Module
// features/samurai/samurai-routing.module.ts
const routes: Routes = [
{ path: '', component: SamuraiListComponent },
{ path: ':id', component: SamuraiDetailComponent },
{ path: ':id/edit', component: SamuraiFormComponent }
];
@NgModule({
imports: [RouterModule.forChild(routes)], // forChild, not forRoot!
exports: [RouterModule]
})
export class SamuraiRoutingModule { }Benefits of Lazy Loading
| Aspect | Without Lazy Loading | With Lazy Loading |
|---|---|---|
| Initial Bundle | Entire application | Only core + home |
| Load time | Long | Short |
| Memory | Everything at once | On demand |
| UX | Long wait | Quick start |
Spotted a mistake in this lesson?
Check yourself
Answer the questions from this lesson. Pick an answer to see right away whether it is correct.
1. Which syntax is correct for lazy loading a module?
2. What is the main benefit that lazy loading of modules provides?
These are 2 of 4 questions for this lesson. Solve the rest in the game.
Hands-on tasks in the game
- Code editor
Complete the routing configuration for lazy loading the SamuraiModule module.
- Horizontal ordering
Arrange the start of lazy loading on a single line (up to the dynamic import):
- Vertical ordering
Order the stages of lazy loading a module after the user navigates to the path:
- Click in order
Click the elements in order to build the call: RouterModule.forChild(