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.