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!

purpose

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="http://xx.com/xx.png" SRC ="" /> // <img data-src="http://xx.com/xx.png" src="http://xx.com/xx.png" />

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="http://xx.com/xx.png" style="background-image: none; background-size: cover;" ">< div style="background-image: url(http://xx.com/xx.png); 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="https://tse1-mm.cn.bing.net/th/id/OIP.8OrEFn_rKe82kqAWFjTuMwHaEo?pid=Api&rs=1" /> </div> <div class="img"> < img class = "PIC" Alt = "loading of data -" SRC = "https://ssl.tzoo-img.com/images/tzoo.94911.0.910013.seoul-nami.jpg?width=1080" / > <div class="img"> <img class=" PIC "Alt =" loading" data-src="https://tse4-mm.cn.bing.net/th/id/OIP.ZitgAuABnwkrGn4lid2ZmQHaEK?pid=Api&rs=1" /> </div> <div class="img"> < img class = "PIC" Alt = "loading of data -" SRC = "http://pic34.photophoto.cn/20150315/0034034862056002_b.jpg" / > < / div > < div <img class=" PIC "Alt =" load "> data-src="http://img.mp.sohu.com/upload/20170724/32d4409f34194b029ed287abf1c99b70_th.png" /> </div> <div class="img"> < img class = "PIC" Alt = "loading of data -" SRC = "https://pic6.wed114.cn/20180829/2018082910075991913520.jpg" / > < / div > < div <img class=" PIC "Alt =" load "> data-src="https://tse4-mm.cn.bing.net/th/id/OIP.PZdPKj3sXEX2jLrepx3MUwHaEo?pid=Api&rs=1" /> </div> <div class="img"> < img class = "PIC" Alt = "loading of data -" SRC = "https://pic6.wed114.cn/20180829/2018082910075831439349.jpg" / > < / div > < div Class = "img" > < img class = "PIC" Alt = "loading of data -" SRC = "https://pic6.wed114.cn/20180829/2018082910075468043336.jpg" / > < / div > <div class="img"> <img class=" PIC "Alt =" loading" data-src="https://tse2-mm.cn.bing.net/th/id/OIP.CRYz5Bv4vylsMh83G4CsLgHaFj?pid=Api&rs=1" /> </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(() => { fn.call(this, 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

summary

  • 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