Lazy Load Images in Angular

This guide explains how to set up a Lazy load of images in Angular. The Images are better at conveying a message. It also results in better user experience. A picture is worth a thousand words is an old saying which means a picture may convey an idea more quickly and effectively than the written word.

Why Lazy Load Images?

With the images comes the issue of Page Load speed. More images you have slower it takes to download them and display them to users. Page load speed is a very important factor determining the user experience and also one of the factors in Ranking.

You can optimize the image size using services like ShortPixel, which vastly reduces the size of images. But it won’t be enough if you have many images on the page. This is where the lazy loading of the images comes into picture

What is Lazy Loading?

Lazy Loading Images is a technique, where we delay the loading of images until we need them. For Example, load only those images which are above the fold. The images below the fold are loaded only when the user scrolls to that location. This helps to load the page the quickly.

Lazy Load Images in Angular

There are many third-party libraries available. One of the popular package is ng-lazyload-image.

Import LazyLoadImageModule in Root Module or Shared Module

Open the app.component.ts. In a img element assign the image to lazyLoad directive using the property binding.

The complete app.component.ts is as below

Run the app. As you scroll down you will see that images are lazily loaded.

Lazy Load Images in Angular using ng-lazyload-image

Default Image

You can specify an optional default image as shown below

Background Image

Responsive Images

You can also use the useSrcSet property to display the Responsive images

Debug

Another important feature of the library is the debugging feature. Use the  [debug]="true" and see the debug information in the web console.

Angular Universal

The library does not seems to work correctly with Angular Universal due to Image delivered by Universal are reloaded causing a flash

References

  1. ng-lazyload-image
  2. Github
  3. Lazy Load Issue with Angular Universal

2 thoughts on “Lazy Load Images in Angular”

Leave a Comment

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top