Back to course

Lazy Loading Feature Modules

The Complete Angular Developer: From Zero to Hero

40. Lazy Loading Feature Modules

For large applications, loading all code at startup leads to slow load times. Lazy Loading is an optimization technique that loads feature modules only when the user navigates to their routes.

Prerequisites: Feature Modules

To lazy load, the application must be split into functional modules (e.g., AdminModule, UsersModule) that are not imported by the AppModule.

CLI command to create a module with routing:

bash ng g module admin --route admin --module app

This creates AdminModule and automatically configures the lazy load route in AppRoutingModule.

Configuring the Lazy Load Route

Instead of providing a component, the lazy load route uses loadChildren and dynamic import() syntax, which leverages modern JavaScript features to create a separate bundle.

app-routing.module.ts:

typescript const routes: Routes = [ { path: '', redirectTo: 'home', pathMatch: 'full' },

// Standard Eagerly Loaded Route { path: 'home', component: HomeComponent },

// Lazy Loaded Route // When the user navigates to /admin, Angular loads the AdminModule file dynamically. { path: 'admin', loadChildren: () => import('./admin/admin.module').then(m => m.AdminModule) } ];

The Effect on Performance

When you run a production build, Angular's build process separates the code into multiple bundles (chunks). The root bundle remains small, and the feature module bundles are loaded asynchronously on demand. This significantly improves initial application load time.

Note: Guards can be applied to lazy-loaded routes just like regular routes. The guard is executed before the module bundle is downloaded.