Lazy Loading in Angular

An angular app is made of multiple components, If your app has few components then it will take not much time to load in the browser but what if your application has lots of components. The loading time will be increased and this will not leave a good impression.

Ok, don't feel bad for your users, Angular has everything that you or your user expect from a web app. and here in this case it's called lazy loading.

Lazy loading is loading the components as and when required. So If a module is lazy loaded then it will not initially load, the module will load only when it is asked to.

Let's start with an example:

First execute below two commands to generate two modules with routing feature enabled:

ng generate module module a --route a --module app.module
ng generate module module b --route b --module app.module

After that your app-routing.module.ts will have below routes defined:

{ path: 'a', loadChildren: () => import('./module-a/module-a.module').then(m => m.ModuleAModule) },
    { path: 'a', loadChildren: () => import('./module-b/module-b.module').then(m => m.ModuleBModule) }

It means module-a will only load when path 'a' is accessed and the same goes with module-b as well.

If you load your app in the browser initially you will not see any thing loaded related to module-a and module-b.

Now click on Load module-a or Load module-b, you will see these modules loaded in the browser now.

So that's the basic knowledge of loading modules on demand in angular or lazy loading.

Did you find this article valuable?

Support Subham Kumar's Blog by becoming a sponsor. Any amount is appreciated!