Lazy Load Images in Angular with Two Lines of Code

Netanel Basal
Netanel Basal
Published in
2 min readAug 25, 2020

Image lazy loading defers the loading of an image that isn’t currently visible in the viewport. Such an image will be loaded only when the user scrolls and the image becomes visible. Using this technique, we can gain better performance and load time.

Today modern browsers added native support for lazy loading images, and we can benefit from it by adding one simple attribute to our img element:

The loading attribute supports three options — auto, eager, and lazy. Setting it to lazy will defer the loading of the resource until it reaches a calculated distance from the viewport.

Browser support

Let’s create a directive that seamlessly adds this attribute if the browser supports it:

We check if the browser supports this feature. If that’s the case, we add the loading attribute; Otherwise, we leave the default behavior.

We can also take it one step further and fallback to an IntersectionObserver implementation, which is supported by all browsers (except IE).

🚀 In Case You Missed It

Here are a few of my 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

And many more!

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

--

--

Netanel Basal
Netanel Basal

Written by Netanel Basal

A FrontEnd Tech Lead, blogger, and open source maintainer. The founder of ngneat, husband and father.