Skip to content

How to Get Killer Page Performance With Angular Lazy Loading

Angular is a popular open-source framework that offers a simplified process for building web applications. The framework is based on TypeScript, a superset of JavaScript—with additional features like static typing, interfaces, and classes—that promotes component-based development, ensuring that components are decoupled and easily reusable.

Images are a critical factor of page-load times in most web applications. A common strategy for improving load performance is to lazy-load images, which means waiting to load an image until the viewer scrolls and it actually enters the viewport. This post explains how lazy loading works in Angular and describes how to implement it for your application.

Here are the topics:

Lazy loading is a practice that delays the loading or initialization of elements or components until they are accessed or brought into the viewport, e.g., display the images at the bottom of a page only when the viewer scrolls there.

Lazy loading can improve website performance by—

  • Reducing initial load times: Load only the elements in view, reducing the amount of data to be loaded. Typically, the lighter a page, the faster it loads.
  • Conserving bandwidth: Deliver content only when needed, refraining from sending unnecessary content and saving bandwidth for both the viewers and web servers.
  • Saving system resources: Process and render code only when needed, saving computing and memory resources.

Several Angular component packages are available for implementing lazy loading. Here are two popular ones:

  • ngx-loadable is an open-source, lightweight package for lazy-loading Angular components. The package contains a simple API that supports loading indicators. When using the module, you need to load it only once regardless of the number of pages for loading and the use frequency.
  • hero-loader is an open-source package for lazy-loading Angular modules in response to various triggers, including mouseover, click, and route change. The package is an extension of the built-in capability offered by loadChildren.

Angular supports lazy loading of NgModules out of the box. By default, NgModules are eagerly loaded, meaning that they load immediately when someone accesses the application even if they are not needed then. However, you can create a feature module with the --route flag and then configure the route to lazy-load the module, as follows:

const routes: Routes = [
  {
    path: 'customers',
    loadChildren: () => import('./customers/customers.module').then(m => m.CustomersModule)
  }
];

For more details, including the procedure for setting up lazy loading in the application UI, see the Angular documentation.

You can incorporate lazy loading into your Angular projects with ngx-loadable. Below is a summary of the procedure. For more details, see the full tutorial by Zama Khan Mohammed. The tutorial’s source code is on GitHub.

  1. Install ngx-loadable.

    Install and manage ngx-loadable with YARN or npm. Type:

    npm install ngx-loadable --save

    or:

    yarn add ngx-loadable

  2. Add a module with a bootstrapped component.

    Create a module called login-modal with the CLI commands below. To simplify things and avoid extra configuration in ngx-loadable, give the module and component the same name and place the module in the src/app folder.

    > ng g m login-modal
    > ng g c login-modal -m login-modal
    

    Add the component to bootstrap, as follows:

    import { NgModule } from '@angular/core';
    import { CommonModule } from '@angular/common';
    import { LoginModalComponent } from './login-modal.component';
    
        @NgModule({
      imports: [
        CommonModule
      ],
      declarations: [LoginModalComponent],
      bootstrap: [LoginModalComponent]
    })
    export class LoginModalModule {
    }
    
  3. Add the component to the lazyModules array.

    Now add the path of loginModalModule to the lazyModules array.

    {
      ...
      "projects": {
          ...
          "architect": {
            "build": {
              "options": {
                ...
                "lazyModules": [
                  "src/app/login-modal/login-modal.module"
                ]
              }
              ...
          }
        }
    }
    
  4. Lazy-load the login module with ngx-loadable.

    Lazy-load the new module you created with ngx-loadable. The code example below preloads loginModalModule and displays it on a mouseover. If loading is still in progress, the module displays the message “Loading ….”

    Alternatively, use the ngx-perimeter flag to preload modules based on how near the mouse is to an element. If the content is in the viewer’s viewpoint, run ngxInViewport to show the content.

Cloudinary is a cloud-based service that simplifies and automates the process of manipulating and delivering images and videos, optimized for all devices regardless of bandwidth. The Advanced Image component in Cloudinary performs many common front-end tasks on images, including lazy loading, progressive image optimization, placeholding, and according accessibility. With Advanced Image, you can lazy-load images through a placeholder by running just two lines of code after installing the Angular SDK, as follows:


   

  • The loading=”lazy” attribute specifies that loading occurs only when the image appears in the viewport.
  • The cl-placeholder tag enables you to define a placeholder that is shown while the image is loading. The type attribute has four options: Blur, Pixelate, Vectorize, and Predominant Color.

LQIP

Sign up for Cloudinary pronto! We offer generous free plans to get you started.

Back to top

Featured Post