Lazy loading

Lazy loading means we don't start with all of the application loaded initially. Parts of our application can be cordoned off into chunks that are only loaded when you ask for them. Today, this is centered around routes, this means that if you ask for a specific route you have not visited before, the module and all its constructs will be loaded. This is not something that is there by default but something you can quite easily set up.

Let's have a look at an existing module and its routes, and see how we can turn that into a lazy-loaded module. We will have to make changes in the following places :

  • The routes list for our feature module
  • Add a route entry in our application routes, with a specific lazy-load syntax
  • Remove all references to the feature module in other modules

First, a quick look at our feature modules routing list, prior to the change:

// app/lazy/routes.ts
let routes = [{
path : 'lazy',
component : LazyComponent
}]

// app/lazy/lazy.module.ts
@NgModule({
imports: [RouterModule.forChild(routes)]
})
export class LazyModule {}

Our first order of business is to change the path for the first route entry from lazy to '', an empty string. It sounds a bit counterintuitive, but it has an explanation.

The second thing we do is to remedy the first thing; we need to add a lazy route entry to our app module routing, like so:

// app/routes.ts
let routes = [{
path: 'lazy',
loadChildren: 'app/lazy/lazy.module#LazyModule'
}];

As you can see, we add the loadChildren property and this property expects a string as a value. This string value should point to where the module can be found, so essentially it looks like <path to the module from the root>#<Module class name>.

The last step is to remove all references to this module in other modules, for a very natural reason: if you haven't navigated to /lazy, a service or component and so on doesn't really exist yet, as its bundle hasn't been loaded to the application.

Finally, let's have a look at what this looks like in the debug mode. The first image will show what it looked like before we navigated to our lazy module:

Here, we have our normal bundles that our project setup produces. Let's now navigate to our lazy route:

We can see that a bundle has been added called 5.chunk.js, and it contains our newly loaded module and all its constructs.

A little word of caution though, is to not place constructs in lazy-loaded modules that you think you will use elsewhere. Conversely, you can let your lazy module depend on services and constructs found in other modules, as long as those are not lazy loaded. A good practice is therefore, to make as many modules as possible lazy loaded but shared functionality can't be lazy loaded, for the above mentioned reason.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset