Cloudinary Blog

How to Get Killer Page Performance With Angular Lazy Loading

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:


How to Optimize for Page Load Speed


What Is Lazy Loading?

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.

Why Should You Care About Lazy Loading in Angular?

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.

What Are the Ways in Which to Lazy-Load in Angular?

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:

Copy to clipboard
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.

How Do You Implement Lazy Loading With ngx-loadable?

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.

    Copy to clipboard
    > ng g m login-modal
    > ng g c login-modal -m login-modal

    Add the component to bootstrap, as follows:

    Copy to clipboard
    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.

    Copy to clipboard
    {
    ...
    "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.

How Do You Lazy-Load Images in Angular With Cloudinary?

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:

Copy to clipboard
<cl-image loading=”lazy” public-id=”bear” width=”500”>
   <cl-placeholder type=”pixelate”></cl-placeholder>
<cl-image>
  • 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.

Want to Learn More About Lazy-Loading?

Recent Blog Posts

Laravel File Upload to a Local Server Or to the Cloud

Currently, Laravel is the most renowned PHP framework, boasting of a large developer community; several open-source packages, such as Cashier, Sanctum, Scout, and Telescope; and a host of paid platforms, e.g., Laravel Forge, Envoyer, and Vapor. Laravel Forge & Envoyer ably supports deployment and use of Laravel production-based apps.

Read more
TedsVintageArt.com Automates Generation of Captivating Product Images on Cloudinary

At TedsVintageArt.com, we digitally restore historic maps and sell their art prints on multiple platforms, such as Amazon, Etsy, eBay, and Houzz. As our operations ramped up years ago, it took an inordinately long time to generate custom images for our products. Plus, since we sell art, it behooves us to produce multiple high-quality images for each print, which was another time-consuming task.

Read more
lastminute.com Takes a Vacation From Media-Management Headaches With Cloudinary

As a 20-year online leader in travel and leisure retail, Europe-based public company lastminute.com along with its 1,200 employees are committed to enriching the lives of vacationers through comprehensive and enticing products and services. Beyond flight deals and tours, it's the images and videos, whether of that luxury villa in Greece, romantic Parisian street, or exotic stroll through the Marrakech markets, that attract audiences and boost bookings.

Read more