Skip to main content

How to lazy load images in Angular 6

Lazy loading is a technique to load the content only when the user asks for it. Therefore, the initial loading of the webpage is much faster as the complete page is not loaded. In case of lots of images on the webpage, it is always recommended to use lazy loading for the images. As an example, while showing a photo gallery, there is no point loading all the images in one go as the user may leave after only viewing the first few images and this would result in slower loading and waste of bandwidth. In such scenarios, lazy loading is an ideal choice. This post talks about how to lazy load images in Angular 6.

How to lazy load images in Angular 6

‚Äč

If you want to learn all of Angular, I want to personally recommend ng-book as the single-best resource out there. You can get a copy here.

To lazy load images, we will use ng-defer-load library. ng-defer-load is an Angular directive to load elements lazily. It uses Intersection Observer API to check if an element is in the viewport and falls back to scroll detection mechanism for unsupported browsers. It can also be used to lazy load any element in your angular application. First, install the ng-defer-load via npm.

npm i @trademe/ng-defer-load

Install the angular cli (ignore if already installed).

npm install -g @angular/cli

Let’s create an angular application.

ng new LazyLoadAngular

Once the application is created, open app.module.ts and import the ng-defer-load module. Like,

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { DeferLoadModule } from '@trademe/ng-defer-load';

import { AppComponent } from './app.component';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule, 
    DeferLoadModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

For this post, we’ll create an image collection with 2 properties URL and show. The URL property will have the image URL and show property indicates when the image should be displayed. Initially, the value of show property will be false for all the images. For the demo, I am using loremflickr placeholder images.

The below code creates a collection of 50 random images from loremflickr and populates the imageList collection.

export class AppComponent {
  imagesList = [];
  constructor() {
    for (let i = 0; i < 50; i++) {
        const url = 'https://loremflickr.com/640/480?random=' + (i +1);
        this.imagesList[i] = {
          url: url,
          show: false
      };
    }
  }
}

As mentioned earlier, the ng-defer-load uses Intersection Observer API to check if an element is in viewport and falls back to scroll detection mechanism for unsupported browsers. So, inside the HTML, we’ll loop through the image collection and use deferLoad directive of the ng-defer-load library to check if the image is in viewport. If yes, then set the show property to true to display the image. Like,

<div class="images" *ngFor="let image of imagesList" (deferLoad)="image.show = true">
    <ng-container *ngIf="image.show">
      <img src={{image.url}}>
    </ng-container>
</div>

Here, we’ll have to take care of one thing. Make sure to assign a fixed height to the container, otherwise lazy loading will not work. To do that either you can use the inline style to set the height or create a CSS class to set the height. Like,

.images {
    height:480px;
    padding-top: 10px;
}

That’s it. You can check the working demo here and the code is available here.

This angular library can be used for lazy loading any angular element, it’s not limited to images.

Thank you for reading and I hope it helped you. Keep visiting this blog and share this in your network. Please put your thoughts and feedback in the comments section.

PS: If you found this content valuable and want to return the favour, then Buy Me A Coffee

One thought on “How to lazy load images in Angular 6

Leave a Reply

Your email address will not be published. Required fields are marked *