Lazy Load Images in 30 Lines Of Code

Angular Directive for lazy loading images with Intersection Observer

Tomasz Kula
2 min readJun 4, 2018

The goal of this article is to create a directive for lazy loading images after they enter the viewport.

Lazy Load Images

We start off by creating the directive.

We stop the image from loading immediately with the use of @HostBinding(). As long as srcAttr is set to null, the image will not attempt to load.

We also expose the src @Input() property to capture the reference to the intended image’s source.

When we decide to load the image, we must set the srcAttr to the value stored in the src property.

Next, we have to implement the lazy loading logic.

To detect the images entering the viewport, we will use the experimental browser API — Intersection Observer.

The Intersection Observer API lets code register a callback function that is executed whenever an element they wish to monitor enters or exits another element (or the viewport).

Because the Intersection Observer is an experimental API, we must check if it is supported, before we attempt to use it.

All that is left to do, is to implement the lazyLoadImage method.

The Intersection Observer constructor takes two arguments.

First argument is a callback function that will be called when the image enters or leaves the viewport. The second argument, is an options object that lets you control the circumstances under which the observer’s callback is invoked.

We chose not to pass the options as the second argument to Intersection Observer constructor, because the defaults work very well in this example. If you want finer control over the intersection process, make sure to check out this MDN article.

Inside the callback function, we check if the image isIntersecting with the current viewport. If it is, we load the image and stop the observing process.

To kick off the observing process, we call the observe method on the observer instance with the reference to the image element, that the img[appLazyLoad] directive is attached to.

And that’s it! We have a working image lazy loading directive in just over 30 lines of code.

If you like the content, please clap 👏👏👏

To read more about Angular, follow me on Medium or Twitter.

--

--