Dynamic & Lazy Loading in Angular

Dynamic & Lazy Loading in Angular

Hi Folks,

Though many of you working as an angular developer knows what is lazy loading and even the newbie will get it correct as the word says lazy loading — on demand loading of the module. So what does it exactly means ?

So, we have some structure like this when you are not using Lazy loading

Without Lazy load

If you wrote all your code for your whole module like this it would be loading all things when the user hit the page or we can say on the page load but we can make a couple of changes and we can lazy load our different routes and our different bundles and

With Lazy load.

in this scenario, if the user hits the dashboard route, it will load the dashboard module on-demand and same with Auth module and so on. So in our app, it will be split out into three different bundles and contain everything they need to execute those different modules.

Behind the Scenes, what's happening in Angular CLI

What happens is:- These modules fed into the CLI and then the CLI feds them into Webpack or any other build tool and outputs Javascript File and then the browser loads that in the run time engine.

So what exactly is happening when you write this

Lazy loading using loadChildren

The first part here in red is the path to the bundle, the ngModule bundle that we are trying to lazily load. What actually it says is:-

  1. Tells the Webpack to create a separate bundle.
  2. Loads the bundle when the route is visited.

Now, what is the second half (Blue) do?

Answer: — So the second half is a function that talks to an interface called NgModuleFactoryLoader and in Angular the implementation for NgModuleFactoryLoader is called SystemJsNgModuleFactoryLoader. So what it does is:-

  1. Forces the download of the bundle.
  2. Loads the Dashboard module into Angular so it can be used by the Router Module ( It loads the whole module into Angular so that it can be reused by the Routing Module).
  3. Router loads the corresponding component.

This is how lazy loading works behind the scenes with Angular CLI and Webpack.

Will talk about the Misconception of lazy loading in Angular.

Please share & subscribe and stay tuned for the next part.