0
0
Angularframework~5 mins

Lazy loading routes and modules in Angular

Choose your learning style9 modes available
Introduction

Lazy loading helps your app load faster by only loading parts when needed. It keeps the app small at start and loads extra features later.

When your app has many pages or features that users may not visit right away.
To improve initial load speed by loading big modules only on demand.
When you want to split your app into smaller chunks for easier maintenance.
If you want to reduce data usage for users by loading code only when needed.
Syntax
Angular
const routes: Routes = [
  {
    path: 'feature',
    loadChildren: () => import('./feature/feature.module').then(m => m.FeatureModule)
  }
];

The loadChildren property uses a function that returns a dynamic import.

This syntax tells Angular to load the module only when the user navigates to the 'feature' path.

Examples
This example lazy loads the DashboardModule when the user visits '/dashboard'.
Angular
const routes: Routes = [
  {
    path: 'dashboard',
    loadChildren: () => import('./dashboard/dashboard.module').then(m => m.DashboardModule)
  }
];
This example redirects the empty path to 'home' and lazy loads HomeModule for '/home'.
Angular
const routes: Routes = [
  {
    path: '',
    redirectTo: 'home',
    pathMatch: 'full'
  },
  {
    path: 'home',
    loadChildren: () => import('./home/home.module').then(m => m.HomeModule)
  }
];
Sample Program

This routing setup lazy loads the ProductsModule when the user navigates to '/products'. The empty path redirects to '/products'. This keeps the initial app bundle small and loads product features only when needed.

Angular
import { Routes } from '@angular/router';

export const routes: Routes = [
  {
    path: 'products',
    loadChildren: () => import('./products/products.module').then(m => m.ProductsModule)
  },
  {
    path: '',
    redirectTo: 'products',
    pathMatch: 'full'
  }
];
OutputSuccess
Important Notes

Lazy loading improves app speed but requires modules to have their own routing setup.

Use Angular DevTools or browser network tab to see lazy loaded chunks being fetched.

Always test lazy loaded routes to ensure modules load correctly without errors.

Summary

Lazy loading delays loading modules until needed, speeding up app start.

Use loadChildren with dynamic import syntax in route definitions.

Helps manage large apps by splitting code into smaller, on-demand pieces.