Lazy loading is a technique in Angular that allows you to load JavaScript components asynchronously when a specific route is activated. This can add some initial performance during the initial load, especially if you have many components with complex routing. Lazy loading modules helps us decrease the startup time. With lazy loading our application does not need to load everything at once, it only needs to load what the user expects to see when the app first loads. Modules that are lazily loaded will only be loaded when the user navigates to their routes.
So far this is a very common module that relies on the BrowserModule, has a routing mechanism and two components: AppComponent and EagerComponent. For now, let's focus on the root component of our application (AppComponent) where the navigation is defined.
Our navigation system has only two paths: eager and lazy. To know what those paths are loading when clicking on them we need to take a look at the routing object that we passed to the root module.
Here we can see that the default path in our application is called eager which will load EagerComponent.
But more importantly, we can see that whenever we try to go to the path lazy, we are going to lazy load a module conveniently called LazyModule. Look closely at the definition of that route:
{ path: 'lazy', loadChildren: 'lazy/lazy.module#LazyModule' }
There's nothing special about LazyModule other than it has its own routing and a component called LazyComponent.
The routing object is very simple and only defines the default component to load when navigating to the lazy path.
export const routing: ModuleWithProviders = RouterModule.forChild(routes);Notice that we use the method call forChild instead of forRoot to create the routing object. We should always do that when creating a routing object for a feature module, no matter if the module is supposed to be eagerly or lazily loaded. Finally, our LazyComponent is very similar to EagerComponent and is just a placeholder for some text.
When we load our application for the first time, the AppModule along the AppComponent will be loaded in the browser and we should see the navigation system and the text "Eager Component". Until this point, the LazyModule has not being downloaded, only when we click the link "Lazy" the needed code will be downloaded and we will see the message "Lazy Component" in the browser.
No comments:
Post a Comment