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:

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

Our $2B Valuation

By
Blackstone Growth Invests in Cloudinary

When we started our journey in 2012, we were looking to improve our lives as developers by making it easier for us to handle the arduous tasks of handling images and videos in our code. That initial line of developer code has evolved into a full suite of media experience solutions driven by a mission that gradually revealed itself over the course of the past 10 years: help companies unleash the full potential of their media to create the most engaging visual experiences.

Read more
Direct-to-Consumer E-Commerce Requires Compelling Visual Experiences

When brands like you adopt a direct–to-consumer (DTC) e-commerce approach with no involvement of retailers or marketplaces, you gain direct and timely insight into evolving shopping behaviors. Accordingly, you can accommodate shoppers’ preferences by continually adjusting your product offering and interspersing the shopping journey with moments of excitement and intrigue. Opportunities abound for you to cultivate engaging customer relationships.

Read more
Automatically Translating Videos for an International Audience

No matter your business focus—public service, B2B integration, recruitment—multimedia, in particular video, is remarkably effective in communicating with the audience. Before, making video accessible to diverse viewers involved tasks galore, such as eliciting the service of production studios to manually dub, transcribe, and add subtitles. Those operations were costly and slow, especially for globally destined content.

Read more
Cloudinary Helps Minted Manage Its Image-Generation Pipeline at Scale

Shoppers return time and again to Minted’s global online community of independent artists and designers because they know they can count on unique, statement-making products of the highest quality there. Concurrently, the visual imagery on Minted.com must do justice to the designs into which the creators have poured their hearts and souls. For Minted’s VP of Engineering David Lien, “Because we are a premium brand, we need to ensure that every single one of our product images matches the selected configuration exactly. For example, if you pick an 18x24 art print on blue canvas, we will show that exact combination on the hero images in the PDF.”

Read more
Highlights on ImageCon 2021 and a Preview of ImageCon 2022

New year, same trend! Visual media will continue to play a monumental role in driving online conversions. To keep up with visual-experience trends and best practices, Cloudinary holds an annual conference called ImageCon, a one-of-a-kind event that helps attendees create the most engaging visual experiences possible.

Read more