Image lazy loading can be simply understood as: when the user browses the web page, only when the page is about to scroll to the location of the image, then the required image is loaded. Instead of loading all the images one by one once the page is opened, even though the user hasn’t scrolled to where the images are at all.

This can significantly improve the speed of page load completion when there are more images on a page. If the page itself is long and the user doesn’t scroll to the image location, it doesn’t make much sense to load out the image and waste a lot of server bandwidth and traffic. So usually image lazy loading technique is used.

The IntersectionObserver API-based approach

I mentioned using the IntersectionObserver API to calculate whether two HTML elements intersect in my article “Use of IntersectionObserver API, Element Intersection/Visibility Determination and Implementation of Inert Image Loading”. The meaning of “intersection” is that they appear in the viewable area of the browser. Determining intersection can do a number of things.

  • Inert loading: load the image element when it enters the browser window
  • Infinite scrolling: continue to load more content when the bottom element of the page appears
  • Calculate ad presentation: if the ad doesn’t even appear, is the ad wasted?
  • On-demand animation: render a certain animation when the user scrolls to a certain area

This approach is very simple to implement, but requires a transformation of the target HTML file.

  • <img src="" /> needs to be changed to <img data-src="" />.
  • Need to use a script to determine if it intersects, and if it does, set data-src of <img> to src.

This is bound to be a bit tricky.

There is another scenario that I encountered on my blog: because most RSS readers do not support the execution of JS scripts. So if the RSS reader is used to read the article, there is a problem with the image not loading because the src of the img is missing.

In general, using the IntersectionObserver API is perfectly adequate, but it always feels a bit overkill. So, a more intuitive way of using it has emerged.

Based on the loading=lazy approach

lazy loading, lazy loading, just add a loading=lazy to img?

Indeed, it really works now.

<img src="main.png" loading="lazy" width="100" height="100"/>

It’s that simple.

In general, width and height should be there as much as possible (it’s okay to write them in style), otherwise lazy loading may not work on Chrome.

See this demo for an example of how this works:

With this native support, I deleted a big chunk of code!