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, 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.

Recent Blog Posts

Automatic Video Creation for Social Media at Scale

With video becoming increasingly popular, especially across social media, it’s as important as ever to ensure that your videos aren’t one of the hundreds that people just scroll on past. There’ve been a few successful techniques over the last couple of years to help with that, such as—

Read more
Uploading, Managing and Delivering PDFs With Cloudinary

The Portable Document Format (PDF) is a popular format developed by Adobe for delivering formatted text and images. A PDF file includes a complete description of all layout elements, including text, fonts, images and layers, ensuring that the file will look identical when opened on any device. The PDF format also has the big advantage of compressing high-quality files to a relatively small file size.

Read more
Share Your DAM Assets! New Visual Collections + Media Portal

If you've been working at home with young kids around during these “corona days”, you might have intuitively expected the last word of the title above to be "Toys" or "Candy"   😜. However, if you're a member of a creative team for a web site or software application, then you know how essential it is to have simple ways to share and collaborate on pre-production media assets.

Read more