Making Use of Lazy Loading

Let's explore how we can make use of lazy loading for optimizing our application for production.

Another way performance can be improved is through the use of lazy loading within our application. Back in NgModules chapter, we introduced you to the concept of modules in Angular. This is how our application is structured using a module. This contains all the Components, Services, Templates, and other files that are needed for a section.

Implement lazy loading

Through modules, we can create feature modules. These are modules that contain all the functionality of a section of our application (think of ClientModule or CompanyModule of our demo application). Through the use of modules, we can use lazy loading to only load the modules (and the code contained within that module) when needed.

app-routing.module.ts file

Lazy loading is configured through the Routes of our application. Usually, we would load the main component for a route like this:

{
   path: 'clients/new',
   component: ClientPageComponent
},

Instead, we set up the Route so that it loads the module that the Component belongs to, like this:

{
    path: 'clients/new',
    loadChildren: './client/client.module#ClientModule'
},

client.module.ts file

Then, within the ClientModule, we have a local route to load the individual Routes within that module. So if we need to client/new or client/search, these two Routes are defined in the ClientModule itself, like this:

const routes: Routes = [
   {
       path: 'new',
       component: ClientPageComponent
   },
   {
       path: 'search',
       component: ClientSearchPageComponent
   }];

Get hands-on with 1400+ tech skills courses.