First screen optimization lazy loading

Lazy-load. It is optimized for image loading time: Larger sites in the pictures (such as e-commerce sites home page, or group-buying websites, games, home page, etc.), if we try when the user opens a page, put all of the images to load resources, that is likely to cause the phenomenon such as white, caton, because there are too many pictures really, relief handle so many tasks, the browser can’t do!


Lazy loading is an optimized way to load images when they are within the user’s view of the page.

Can increase the speed of the first screen load, after all, it opens at the user page, presented to him is only the first screen, we just put the first screen resource loading picture processing is ok, as for the image below, when a user declines, when the current position is no problem in loading out, pressure is small for performance, user experience and no variation.

The principle of

When the page is initialized, the image’s SRC is actually placed on the data-src attribute. When the element is within visual range, the data-src is assigned to the SRC attribute, completing the image load.

// <img data-src="" SRC ="" /> // <img data-src="" src="" />

Use the background image to achieve, the principle is the same, put background-image, in the visual range, data-src is assigned to the SRC attribute, complete the image loading.

// <div data-src="" style="background-image: none; background-size: cover;" ">< div style="background-image: url(; background-size: cover;" ></div>

Implement a lazy load

Based on the above implementation ideas, their own implementation of a lazy load.

Create a new index. HTML and set the img tag for these images:

<head> <style> .img { width: 200px; height: 200px; background-color: gray; margin-bottom: 20px; } .pic { width: 100%; height: 100%; } </style> </head> <! -- The picture is from the Internet, invaded and deleted. --> <body> <div class="container"> <div class="img"> <! <img class=" PIC "Alt =" loading" data-src="" /> </div> <div class="img"> < img class = "PIC" Alt = "loading of data -" SRC = "" / > <div class="img"> <img class=" PIC "Alt =" loading" data-src="" /> </div> <div class="img"> < img class = "PIC" Alt = "loading of data -" SRC = "" / > < / div > < div <img class=" PIC "Alt =" load "> data-src="" /> </div> <div class="img"> < img class = "PIC" Alt = "loading of data -" SRC = "" / > < / div > < div <img class=" PIC "Alt =" load "> data-src="" /> </div> <div class="img"> < img class = "PIC" Alt = "loading of data -" SRC = "" / > < / div > < div Class = "img" > < img class = "PIC" Alt = "loading of data -" SRC = "" / > < / div > <div class="img"> <img class=" PIC "Alt =" loading" data-src="" /> </div> </div> </body>

In lazy loading implementations, there are two key values: one is the height of the current visible area, and the other is the height of the element from the top of the visible area.

The height of the current viewing area, in modern browsers and Internet explorer browser, you can use window. The innerHeight attribute access, the use of the document in lower version of IE. DocumentElment. ClientHeight access, here we are compatible with two kind of situations:

const viewHeight = window.innerHeight || document.documentElement.clientHeight;

Here we use the getBoundingClientRect() method to get the size of the returned element and its position relative to the size. For this API, MDN explains:

Element. GetBoundingClientRect () method returns the Element size and its position relative to the viewport.

One of the attributes that is returned is the height relative to the top of the viewable area, which is the top attribute, which is exactly how far we want the element to be from the top.

In this way, both properties are obtained.

We useThe height of the current viewable areaGreater than or equal toThe height of the element from the top of the visible areaWe can determine if the element is already visible:

< script > / / get all the pictures of tag const imgs = document. The getElementsByTagName (" img "); / / get the height of the viewing area const viewHeight = window. The innerHeight | | document. The documentElement. ClientHeight; Let num = 0; // let num = 0; Function lazyload() {console.log(" scroll...") ); for (let i = num; i < imgs.length; Let distance = viewheight-imgs [I].getBoundingClientRect().top; If (distance >= 0) {// Write the true SRC to the element, Imgs [I].src = imgs[I].getattribute ("data-src"); Num = I +1; num = I +1; }}} function debounce(fn, delay = 500) {let timer = null; return function (... args) { if (timer) clearTimeout(timer); timer = setTimeout(() => {, args); }, delay); }; } // Yes page initialization is to load the first screen image window.onload = lazyLoad; Window.addeventlistener (" Scroll ", debounce(lazyload, 600), false); window.addeventListener (" Scroll ", debounce(lazyload, 600), false); </script>

Image lazy loading – Online preview


  • Collect everything on the pageimgCan also be usedclass).
  • Gets the height of the view and calculates the displayed heightimgTo avoid repeated assignmentssrc.
  • When sliding the mouse down, it will triggeronScrollEvent (stabilization), and then triggers the calculation of whether to assignsrc.

The resources

  • Front-end performance optimization principles and practices booklet