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

Automation Frees Up PetRescue’s Staff to Help Pets Find Their Forever Homes

As we spend more time at home, many of us are adopting pets for the joy, companionship and a surprising range of health benefits. In Australia, where our nonprofit customer PetRescue is located, there’s a shortage of pets to adopt. Last August, the Guardian reported that dog shelters in Australia emptied and adoption fees for puppies were running as high as $AUS1800.

Read more
Cloudinary and Contentful Make Modern Content Management Easier

I am pleased to share that Cloudinary and Contentful have joined forces to further streamline the creation, processing, and delivery of online content through Cloudinary’s digital asset management (DAM) solution and advanced transformation and delivery capabilities for images and video. What’s more, the partnership delivers a headless approach to DAM. By leveraging APIs for media management tasks, marketers and developers alike benefit from an integrated stack of optimized assets for optimization and automation. As a result, page loads are fast and beautiful, and at scale—with less overhead and effort.

Read more
Introducing Cloudinary's Nuxt Module

Since its initial release in October 2016 by the Chopin brothers as a server-side framework that runs on top of Vue.js, Nuxt (aka Nuxt.js) has gained prominence in both intuitiveness and performance. The framework offers numerous built-in features based on a modular architecture, bringing ease and simplicity to web development. Not surprisingly, Nuxt.js has seen remarkable growth in adoption by the developer community along with accolades galore. At this writing, Nuxt has earned over 30K stars on GitHub and 96 active modules with over a million downloads per month. And the upward trend is ongoing.

Read more
How Quality and Quantity can go Hand in Hand

When it comes to quality versus quantity, you’ll often hear people say, “It’s the quality that counts, not the quantity”. While that’s true in many situations, there are also cases where you want both quality and quantity. You may have thousands of images on your website and you want them all to look great. This is especially important if your website allows users to upload their own content, for example, to sell their own products or services. You don't want their poor quality images to reflect badly on your brand.

Read more
Product Videos 101: What Makes Them Great?

A product’s benefits and usage, including its value proposition, features, and instructive details, are best demonstrated through video. Product-video types vary, depending on the funnel, channel, and audience, the most popular ones being demos, reviews, installation, and how-tos.

Read more