Lazy Load Images in Angular with just a few lines of code!

Tram Ho


Image lazy loading reduces the load of the current image when it is not yet needed to be displayed in the viewport. The like image will only be loaded when the user scrolls to the image to display. Using this technique, we can achieve better performance and load times.

Nowadays, modern browsers have added support for lazy loading images and we can use it by simply adding an attribute to the element. image:

<img src="src.png" alt="Angular" loading="lazy">

Properties loading support three options – auto, eager, and lazy. With the lazy option will delay resource loading until a calculated distance from the viewport is reached.


Let’s create a directive to seamlessly add this attribute if the browser supports it:

First we check if the browser supports this feature or not. If so, we add the loading attribute; If not, we leave it as default.



One more step we can take when the browser doesn’t support it is to call the callback IntersectionObserver ( does not support IE)

In case you missed it Here are some of my open source projects: Akita: State management designed specifically for JS applications Spectator: A powerful tool to simplify tests your perspective Transloco: Angular Internationalization Library Form Manager: A Platform for Proper Form Management in Angular Cashew: A Flexible and Simple Library That Hosts HTTP Requests Error Tailor – Expression Error Seamless pattern for Angular apps And many more!

Reference: Some open source projects:

  • Akita: State Management Tailored-Made for JS Applications
  • Spectator: A Powerful Tool to Simplify Your Angular Tests
  • Transloco: The Internationalization library Angular
  • Forms Manager: The Foundation for Proper Form Management in Angular
  • Cashew: A flexible and straightforward library that caches HTTP requests
  • Error Tailor — Seamless form errors for Angular applications

Follow me on Medium or Twitter to read more about Angular, Akita and JS!

the source:

Share the news now