# Lazy Loading in Angular — A Beginner’s Guide

<!-- wp:heading -->
<h2>What is Lazy Loading?</h2>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>Lazy loading is a process of loading components, modules or other assets of a website as required. Since, Angular creates a <a href="https://en.wikipedia.org/wiki/Single-page_application#:~:text=From%20Wikipedia%2C%20the%20free%20encyclopedia,browser%20loading%20entire%20new%20pages." rel="noreferrer noopener" target="_blank">SPA (Single Page Application)</a>, all of its components are loaded, at once. Secondly, a lot of unnecessary libraries or modules might be loaded as well.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>For a small application it would be okay, but as the application grows the load time will increase, if everything is loaded at once. Lazy loading allows Angular to load components and modules as and when needed.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>First of all, to understand how lazy loading works in Angular, we need to understand the basic building blocks of the framework: NgModules.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>In order to understand how Lazy Loading works we first need to understand the building block of Angular: NgModules.</p>
<!-- /wp:paragraph -->



<!-- wp:heading -->
<h2>What are NgModules?</h2>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>Angular libraries like RouterModule, BrowserModule, FormsModule are NgModules. Angular Material, which is a 3rd party, is also a type of NgModule. NgModule consists of files &amp; code related to a specific domain or having a similar set of functionalities.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>A typical NgModule file declares components, directives, pipes, and services. It can also import other modules that are needed in the current module.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>One of the important advantage of NgModules is they can be lazy loaded.  Let's have a look at how we can configure lazy loading.</p>
<!-- /wp:paragraph -->

<!-- wp:heading -->
<h2>How to Create NgModules</h2>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>In this tutorial, we will create two modules <em>Module</em> <em>A</em> and <em>Module B</em> which will be lazy loaded. On the main screen we will have two buttons for loading each module lazily.</p>
<!-- /wp:paragraph -->

<!-- wp:heading {"level":4} -->
<h4>Create a Project</h4>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>Create a new Angular project <em>lazy-load-demo</em> by executing the below command.</p>
<!-- /wp:paragraph -->

<!-- wp:codemirror-blocks/code-block {"mode":"shell","mime":"text/x-sh"} -->
```
ng new lazy-load-demo --routing --strict --style css
code lazy-load-demo
```
<!-- /wp:codemirror-blocks/code-block -->

<!-- wp:paragraph -->
<p>Here, we are creating a new project with routing. Secondly, the <a href="https://angular.io/guide/strict-mode" target="_blank" rel="noreferrer noopener">strict mode</a> is enabled. Lastly, we are mentioning the stylesheet format to css. The second command opens your project in VS Code. </p>
<!-- /wp:paragraph -->

<!-- wp:heading {"level":4} -->
<h4>Root Module</h4>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>By default, a root module or app module is created under <em>/src/app</em>. Below is the NgModule file created:</p>
<!-- /wp:paragraph -->

<!-- wp:codemirror-blocks/code-block {"mode":"javascript","mime":"application/typescript"} -->
```
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';

import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    AppRoutingModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }
```
<!-- /wp:codemirror-blocks/code-block -->

<!-- wp:paragraph -->
<p>First, we are importing all the required modules and components.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>After that, <em><strong>@NgModule</strong></em> decorator states that AppModule class is a type of NgModule. The decorator accepts <em>declarations, imports, providers, and bootstrap. </em>Here are the descriptions for each of them:</p>
<!-- /wp:paragraph -->

<!-- wp:list -->
<ul><li><strong><em>declarations</em></strong>: The components in this module.</li><li><strong><em>imports</em></strong>: The modules that are required by the current module.</li><li><strong><em>providers</em></strong>: The service providers if any.</li><li><strong><em>bootstrap</em></strong>: The&nbsp;<em>root</em>&nbsp;component that Angular creates and inserts into the&nbsp;<code>index.html</code>&nbsp;host web page.</li></ul>
<!-- /wp:list -->

<!-- wp:heading {"level":4} -->
<h4>Main screen</h4>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>The main screen will have 2 buttons, namely, <strong><em>Load Module A </em></strong>&amp; <strong><em>Load Module B.</em></strong> As the name suggests, clicking these buttons will lazily load each module. </p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>For that, replace your <em>app.component.html</em> file with the contents below:</p>
<!-- /wp:paragraph -->

<!-- wp:codemirror-blocks/code-block {"mode":"htmlmixed","mime":"text/html"} -->
```
<button style="padding: 20px; color: white; background-color: green;" routerLink="a">Load Module A</button>
<button style="padding: 20px; color: white; background-color: blue;" routerLink="b">Load Module B</button>
<router-outlet></router-outlet>
```
<!-- /wp:codemirror-blocks/code-block -->

<!-- wp:paragraph -->
<p>Let's define the modules for routes <em>a </em>&amp; <em>b</em>.</p>
<!-- /wp:paragraph -->

<!-- wp:heading {"level":4} -->
<h4>Lazy Loaded Modules</h4>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>In order to create lazy loaded modules execute the below commands.</p>
<!-- /wp:paragraph -->

<!-- wp:codemirror-blocks/code-block {"mode":"shell","mime":"text/x-sh"} -->
```
ng generate module modulea --route a --module app.module
ng generate module moduleb --route b --module app.module
```
<!-- /wp:codemirror-blocks/code-block -->

<!-- wp:paragraph -->
<p>The commands will generate two folders <em><strong>modulea</strong></em> &amp; <strong><em>moduleb</em></strong>. Subsequently, each folder will contain their own <em>module.ts</em>,<em> routing.ts </em>and <em>component</em> files.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>If you check your <em>app-routing.module.ts</em> you will see the below code for routes.</p>
<!-- /wp:paragraph -->

<!-- wp:codemirror-blocks/code-block {"mode":"javascript","mime":"application/typescript"} -->
```
const routes: Routes = [
  { path: 'a', loadChildren: () => import('./modulea/modulea.module').then(m => m.ModuleaModule) },
  { path: 'b', loadChildren: () => import('./moduleb/moduleb.module').then(m => m.ModulebModule) }
];
```
<!-- /wp:codemirror-blocks/code-block -->

<!-- wp:paragraph -->
<p>It implies that when route <em>a</em> or <em>b </em>is visited load their respective modules lazily. </p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>On running the project with <strong><em>ng serve</em></strong>, you will see the below screen:</p>
<!-- /wp:paragraph -->

<!-- wp:image {"id":517,"width":434,"height":210,"sizeSlug":"large","linkDestination":"none","className":"is-style-twentytwentyone-border"} -->
<figure class="wp-block-image size-large is-resized is-style-twentytwentyone-border"><img src="https://arjavdave.com/wp-content/uploads/2021/04/Screenshot-2021-04-25-at-11.18.55-PM.png" alt="" class="wp-image-517" width="434" height="210"/><figcaption>Home Page </figcaption></figure>
<!-- /wp:image -->

<!-- wp:paragraph -->
<p>On clicking <em>Load Module A</em> button, you will be routed to page <em>a</em>. This is how your screen should look like.</p>
<!-- /wp:paragraph -->

<!-- wp:image {"id":518,"width":483,"height":245,"sizeSlug":"large","linkDestination":"none","className":"is-style-twentytwentyone-border"} -->
<figure class="wp-block-image size-large is-resized is-style-twentytwentyone-border"><img src="https://arjavdave.com/wp-content/uploads/2021/04/Screenshot-2021-04-25-at-11.18.14-PM.png" alt="" class="wp-image-518" width="483" height="245"/><figcaption>Lazily loaded Module A</figcaption></figure>
<!-- /wp:image -->

<!-- wp:paragraph -->
<p>You should see a similar screen that says <strong><em>moduleb works! </em></strong>when clicked on <em>Load Module B.</em></p>
<!-- /wp:paragraph -->

<!-- wp:heading -->
<h2>How to Verify that the Lazy Loading&nbsp;Worked</h2>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>In order to verify the files loaded, open the developer tools by pressing F12. After that, visit the <em>Network</em> tab as you can see in the screenshot below. When you refresh the page it will show few files requested.</p>
<!-- /wp:paragraph -->

<!-- wp:image {"id":540,"sizeSlug":"large","linkDestination":"none","className":"is-style-twentytwentyone-border"} -->
<figure class="wp-block-image size-large is-style-twentytwentyone-border"><img src="https://arjavdave.com/wp-content/uploads/2021/04/Network-Tab-1024x601.jpg" alt="" class="wp-image-540"/><figcaption>Network Tab</figcaption></figure>
<!-- /wp:image -->

<!-- wp:spacer {"height":50} -->
<div style="height:50px" aria-hidden="true" class="wp-block-spacer"></div>
<!-- /wp:spacer -->

<!-- wp:columns {"className":"is-style-default"} -->
<div class="wp-block-columns is-style-default"><!-- wp:column -->
<div class="wp-block-column"><!-- wp:paragraph -->
<p>Go ahead and clear your list of requests by hitting the clear button as shown in the image on the right</p>
<!-- /wp:paragraph --></div>


<!-- wp:column -->
<div class="wp-block-column"><!-- wp:image {"id":521,"width":131,"height":160,"sizeSlug":"large","linkDestination":"none"} -->
<figure class="wp-block-image size-large is-resized"><img src="https://arjavdave.com/wp-content/uploads/2021/04/Screenshot-2021-04-25-at-11.42.21-PM.png" alt="" class="wp-image-521" width="131" height="160"/></figure>
<!-- /wp:image --></div>
</div>


<!-- wp:spacer {"height":50} -->
<div style="height:50px" aria-hidden="true" class="wp-block-spacer"></div>
<!-- /wp:spacer -->

<!-- wp:paragraph -->
<p>When you click on the <em>Load Module A</em>, you will see a request for <em>modulea-modulea-module.js</em> as in the screenshot below. This verifies that the <em>Module A </em>was lazily loaded.</p>
<!-- /wp:paragraph -->

<!-- wp:image {"id":526,"width":419,"height":171,"sizeSlug":"large","linkDestination":"none","className":"is-style-twentytwentyone-border"} -->
<figure class="wp-block-image size-large is-resized is-style-twentytwentyone-border"><img src="https://arjavdave.com/wp-content/uploads/2021/04/Screenshot-2021-04-25-at-11.46.50-PM.png" alt="" class="wp-image-526" width="419" height="171"/><figcaption>Module A Loaded</figcaption></figure>
<!-- /wp:image -->

<!-- wp:paragraph -->
<p>Similarly, when you click <em>Load Module B</em>, the <em>moduleb-moduleb-module.js</em> file is loaded. Hence, verifying that Module B was loaded lazily.</p>
<!-- /wp:paragraph -->

<!-- wp:image {"id":527,"width":452,"height":201,"sizeSlug":"large","linkDestination":"none","className":"is-style-twentytwentyone-border"} -->
<figure class="wp-block-image size-large is-resized is-style-twentytwentyone-border"><img src="https://arjavdave.com/wp-content/uploads/2021/04/Screenshot-2021-04-25-at-11.47.10-PM.png" alt="" class="wp-image-527" width="452" height="201"/><figcaption>Module B Loaded</figcaption></figure>
<!-- /wp:image -->

<!-- wp:heading -->
<h2>Use Cases</h2>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>As we have seen, it’s very easy to create lazy loading modules. There are lots of use cases where they are useful, such as</p>
<!-- /wp:paragraph -->

<!-- wp:list -->
<ul><li>Creating a separate module for pre-login vs post-login screens.</li><li>For an e-commerce website, vendor facing vs customer facing screens can belong to separate modules. You can also create a separate module for payment.</li><li>A separate CommonModule which contains shared components, directives, or pipelines is usually created. Directives like <em>Copy Code</em> button, components like <em>up vote/down vote </em>are usually included in a common module.</li></ul>
<!-- /wp:list -->

<!-- wp:heading -->
<h2>Conclusion</h2>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>For smaller websites, it might not matter much that all the modules are loaded at once. But, as the site grows it's very effective to have separate modules which are loaded as needed.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>Because of lazy loading, load time for the websites can be reduced drastically. This is specially helpful when you are trying to rank higher in SEO's. Even if not, less loading times means better user experience.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>Are you interested in more articles? Check these out:</p>
<!-- /wp:paragraph -->

<!-- wp:list -->
<ul><li><a href="https://arjavdave.com/2021/04/14/learn-test-driven-development-with-integration-tests-in-net-5-0/">Learn TDD with Integration Tests in .NET</a></li><li><a href="https://arjavdave.com/2021/03/31/net-5-setup-authentication-and-authorisation/">How to authenticate &amp; authorise API’s correctly in .NET</a></li><li><a href="https://arjavdave.com/2021/03/22/azure-functions-wkhtmltopdf/">Azure Functions &amp; wkhtmltopdf: Convert HTML to PDF</a></li></ul>
<!-- /wp:list -->
