November 4, 2020

Lazy load component with Angular 10

About Us

Shashikant Devani

What is Lazy Loading?
Lazy loading (also called on-demand loading) is an optimisation technique for the online content, be it a website or a web app.

Table of Contents

  • Blog-Detail ArrowInstead of loading the entire web page and rendering it to the user in one go as in bulk loading, the concept of lazy loading assists in loading only the required section and delays the remaining, until it is needed by the user.
  • Blog-Detail ArrowBy default, NgModules are eagerly loaded, which means that as soon as the app loads, so do all the NgModules, whether or not they are immediately necessary. For large apps with lots of routes, consider lazy loading—a design pattern that loads NgModules as needed. Lazy loading helps keep initial bundle sizes smaller, which in turn helps decrease load times.
  • Blog-Detail ArrowThere are two main steps to setting up a lazy-loaded feature module
  1. Blog-Detail ArrowCreate the feature module with the CLI, using the
    --route
    flag.
  2. Blog-Detail ArrowConfigure the routes.
Prerequisites
  • Blog-Detail ArrowNode version 12.0 installed on your machine.
  • Blog-Detail ArrowVisual Studio Code
  • Blog-Detail ArrowAngular CLI version 10.0
  • Blog-Detail ArrowThe latest version of Angular (version 10.0)
Create a feature module with routing
you’ll need a feature module with a component to route to. To make one, enter the following command in the terminal, where
customers
is the name of the feature module.
  • Blog-Detail ArrowThe path for loading the
    customers
    feature modules is also
    customers
    because it is specified with the
    --route
    option:
    ng generate module customers --route customers --module app.module
  • Blog-Detail ArrowThis creates a
    customers
    folder having the new lazy-loadable feature module
    CustomersModule
    defined in the
    customers.module.ts
    file and the routing module
    CustomersRoutingModule
    defined in the
    customers-routing.module.ts
    file.
  • Blog-Detail ArrowThe command automatically declares the
    CustomersComponent
    and imports
    CustomersRoutingModule
    inside the new feature module.
  • Blog-Detail ArrowBecause the new module is meant to be lazy-loaded, the command does NOT add a reference to the new feature module in the application's root module file,
    app.module.ts
    .
  • Blog-Detail ArrowInstead, it adds the declared route,
    customers
    to the
    routes
    array declared in the module provided as the
    --module
    option.
ng add @nguniversal/express-engine --clientProject project-example
// app-routing.module.ts const routes: Routes = [ { path: 'customers', loadChildren: () => import('./customers/customers.module') .then(m => m.CustomersModule) } ];
Add another feature module
Use the same command to create a second lazy-loaded feature module with routing, along with its stub component
ng generate module orders --route orders --module app.module
  • Blog-Detail ArrowThis creates a new folder called
    orders
    containing the
    OrdersModule
    and
    OrdersRoutingModule
    , along with the new
    OrdersComponent
    source files.
  • Blog-Detail ArrowThe
    orders
    route, specified with the
    --route
    option, is added to the
    routes
    array inside the
    app-routing.module.ts
    file, using the lazy-loading syntax.
// app-routing.module.ts const routes: Routes = [ { path: 'customers', loadChildren: () => import('./customers/customers.module') .then(m => m.CustomersModule) }, { path: 'orders', loadChildren: () => import('./orders/orders.module') .then(m => m.OrdersModule) } ];
Lazy Load Components
To explain the process of lazy loading a component, we are going to start with a simplified version of our
QuizComponent
which simplistically displays the question properties.
  • Blog-Detail ArrowWe will then extend our component by adding Angular Material components. Last but not least, we react to output events of our lazy-loaded component.
  • Blog-Detail ArrowSo, for now, let’s lazy load a simplified version of the
    QuizComponent

    The first step is to create a container element. For this, we either use a real element like a
    div
    or we can use a
    ng-container
    , which does not introduce an extra level of HTML.
<mat-toolbar> <span>Third Rock Techkno</span> </mat-toolbar> <button class="btn btn-primary" (click)="StartQuiz()"> Start Quiz </button> <ng-container #quizContainer class="quiz-container"></ng-container>
  • Blog-Detail ArrowIn our component, we then need to get a hold of the container. To do so, we use the
    @ViewChild
    annotation and tell it that we want to read the
    ViewContainerRef
    .
@ViewChild('quizContainer', {read : ViewContainerRef}) quizContainer : ViewContainerRef;
  • Blog-Detail ArrowWe got the container where we want to add our lazy-loaded component. Next, we need a
    ComponentFactoryResolver
    and an
    Injector
    which we can both get over dependency injection.
A

is a simple registry that maps Components to generated

classes which can be used to create instances of components.
constructor(private cfr: ComponentFactoryResolver, private injector: Injector, private quizService: QuizService) {} const QuizComponent = await import('./quiz/quiz.component'); const QuizFactoy = this.cfr.resolverComponentFactory(QuizComponent); const instance = this.quizContainer.createComponent(QuizFactoy, null, this.injector); instance.question = this.quizService.getNextQuestion();
Once the start button was clicked, we lazy load our component. If we open the network tab, we can see that the
quiz-component.js
chunk is lazy loaded. In the running application, the component is shown, and the Question is displayed.
Advantages of Lazy loading:
  • Blog-Detail ArrowOn-demand loading reduces time consumption and memory usage thereby optimising content delivery. As only a fraction of the web page, which is required, is loaded first thus, the time taken is less and the loading of rest of the section is delayed which saves storage. All of this enhances the user’s experience as the requested content is fed in no time.
  • Blog-Detail ArrowUnnecessary code execution is avoided.
  • Blog-Detail ArrowOptimal usage of time and space resources makes it a cost-effective approach from the point of view of business persons. (website owners)
Disadvantages of Lazy loading
  • Blog-Detail ArrowFirstly, the extra lines of code, to be added to the existing ones, to implement lazy load makes the code a bit complicated.
  • Blog-Detail ArrowSecondly, lazy loading may affect the website’s ranking on search engines sometimes, due to improper indexing of the unloaded content.
Conclusion
Though there are certain pitfalls of lazy loading yet the big advantages, as optimal utilisation of the two major resources (time & space) and many more make us overlook its disadvantages.

Found this blog useful? Don't forget to share it with your network

Featured Insights

Team up with us to enhance and

achieve your business objectives

LET'SWORK

TLogoGETHER