Angular Lazy Loading Modules

· 246 words · 2 minute read

Lazy Loading routes in Angular is an interesting technique that can significantly improve the performance of an Angular app.

Essentially, lazy loading is a smart way of managing your app’s resources. Instead of loading all the modules of your app at the start, lazy loading enables you to split your app into different modules(e.g. feature modules). These modules are then loaded only when the user navigates to their respective routes. This results in creating different JS bundles for each module.

This approach can enhance your app’s performance, especially if it has numerous features or pages. By loading only the necessary parts, we can reduce the initial load time, which is a key factor in user experience.

However, there are a few considerations when implementing lazy loading. For example, if not executed correctly, lazy loading might lead to unexpected delays when users navigate to new routes for the first time. This is because the corresponding module, which is loaded on-demand, gets downloaded only when required.

To lazy load a module, you need to use the loadChildren property of a route definition, and add a dynamic import that will retrieve the bundle when the route activates.

{
  path: 'my-route',
  loadChildren: () => import('./my-module/my-module.module').then(m => m.MyModule)
}

Lazy loading can be a potent tool in your Angular toolkit. It can significantly decrease initial load times, leading to a smoother and more pleasant user experience. However, like any tool, it’s crucial to understand when and how to use it effectively.