1. What is lazy loading?

When we encounter a long web page with many images, we will first load several images in the viewport, and then load other images when the scroll bar reaches the corresponding image position. This type of lazy loading is called lazy loading.

2. Advantages of lazy loading

  • Improve user experience

    Consider a scenario: when we browse Taobao, the page takes a long time to load before it appears, according to the three-second rule, at this point users must have lost patience. However, using lazy loading can greatly speed up the presentation of the page, thus improving the user experience.

  • Reduce server stress

    Imagine a person who has to do a lot of things in a short amount of time. The same goes for the server. By loading lazily, we reduce the workload of the server, giving it time to slow down and deal with things later.

3. Implementation principle

With so much preparation in the front, here comes the key point (knock on the blackboard!!) .

  • clientHeight: Height of browser viewport;
  • scrollTop: rolling shaft rolling distance;
  • offsetTop: The height of the image header from the top of the browser (Note not the height from the top of the viewport);

Our idea for lazy loading is to load only the images displayed in the viewport at first, as you can see from the image above, we can load only the first two images first. So how do you keep images from loading?

You can do this by storing the image’s address on a custom attribute of the IMG element, which is then assigned to the image’s SRC when loading is required.

So the question is, when do I load the images that follow?

This is to load the next image when the top of the next image is about to appear in the viewport as we scroll through the scroll axis.

Ok, now we know what to load the next image. Which brings us to the second question: How do you know when the next picture is about to appear in the viewport?

The height of the image from the top of the browser – offsetTop <= viewport height + the length of the scrollTop. That’s the point!! It’s easy after you understand that

Last question, how do you get itoffsetTop,scrollTop,clientHeightWhat about these three numbers?

  • offsetTop: Direct passageimg.offsetTopYou can get it;
  • scrollTopThrough:document.documentElement.scrollTopTo obtain;
  • clientHeightThrough:document.documentElement.clientHeightTo obtain;

Lazy loading is mainly introduced here, for the above threeapiNot familiar with their own Baidu learning. Just remember that they can get it.

4. Code implementation

  • First of all definehtmlThe structure andCSSStyle;
<! DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, < span style> img {height: 4px; display: block; margin-bottom: 20px; } </style> </head> <body> <! <img data-src="./img-loop/img/1.jpg" Alt =" idle loading 1" /> <img data-src="./img-loop/img/2.png" Alt = "lazy loading 2" / > < img data - SRC = ". / img - loop/img / 3. JPG "Alt =" lazy loading 3 "/ > < img data - SRC =". / img - loop/img / 4. JPG "Alt =" lazy loading 4 "/ > The < img data - SRC = ". / img - loop/img / 5. JPG "Alt =" lazy loading 5 "/ > < / body > < / HTML >Copy the code
  • The following writtenjs;
const imgs = document.getElementsByTagName('img'); Function lazyLoad(imgs) {// Viewport height; const clientH = document.documentElement.clientHeight; // The distance of the scroll, the logical judgment here is to do compatibility processing; const clientT = document.documentElement.scrollTop || document.body.scrollTop; for(let i = 0; i < imgs.length; I++) {// if the viewport height + scroll distance > the distance from the image to the top of the browser to load; / /! Imgs [I].src = imgs[I]. SRC = imgs[I]. SRC = imgs[I]. SRC = imgs[I]. if(clientH + clientT > imgs[i].offsetTop && ! Imgs [I].src) {// The data-xx attribute can be retrieved from the DOM element dataset. imgs[i].src = imgs[i].dataset.src; }}}; // Start loading images displayed in the viewport; lazyLoad(imgs); // Listen for the scroll event, load the following image; window.onscroll = () => lazyLoad(imgs);Copy the code

At this point, we have completed the lazy loading effect of the initial GIF.

5. Performance optimization

In fact, there are many performance optimizations in the above code, such as frequent scroll events that can cause a lot of stress to the browser. We can do an optimization using the throttling function;

  • No optimization before scrollinglazyLoadFunction firing frequently;

  • Optimization using throttling function;
Function throttle(fn, delay) {let timer = null; return () => { if(timer) { return; }; timer = setTimeout(() => { fn(imgs); timer = null; }, delay)}} // Listen to the scroll event, load the following image; window.onscroll = throttle(lazyLoad, 500);Copy the code
  • Optimized effect;


The complete code

The second implementation of lazy loading