Actual project opening, especially e-commerce projects, because there are a large number of picture loading will inevitably affect performance, so the implementation of lazy loading pictures is very necessary.
Knowledge points for lazy loading of pictures
The Data-property of the label is monitored in the viewable area
Implement the principle of lazy loading of pictures
when we hear the picture go into the viewable area, we assign the DATA-SRC to the value to the SRC attribute <script> var Images = Document.queryselectorall (' img '); ES6 method, you can also use the For statement Array.from (images) directly. ForEach ((EL) =>{ el.src = el.dataset.src; }) </script>
Element.getboundingclientrect () method
Rectobject = Object.getboundingclientrect ();
The return value is a Domrect object that is a set of rectangles returned by the method of the element getClientRects()
, that is, a collection of CSS borders associated with the element. The Domrect object contains a set of read-only properties that describe the border,--left, top, right, and bottom, in pixels. Properties other than width and height are relative to the position of the upper-left corner of the viewport.
With this API, it is easy to get the IMG element's vertex position "rectobject.top" relative to the viewport, as long as the value is less than the height of the browser (window.innerheight) to enter the viewable area. If you want to load in advance, you can add a value to the browser's height.
function Isinsight (EL) { const bound = El.getboundingclientrect (); Const ClientHeight = window.innerheight; return bound.top <= clientheight +; }
Implement picture loading
function Loadimg (EL) { if (!EL.SRC) { const Source = el.dataset.src; EL.SRC = source; } }
The function of judging into the visible area and the function of loading the picture are put into the page function, which is called when the page is loaded and scrolled.
function Checkimgs () { Const IMGS = document.queryselectorall (' li img '); Array.from (IMGs). ForEach (El =>{ if (Isinsight (EL)) { loadimg (EL); }} ) } Window.onload = function () { checkimgs (); } Document.onscroll = function () { checkimgs (); }
This completes the picture lazy loading, but there are some performance problems, such as: the loaded image does not need to traverse, two times the time interval is very short (jitter problem). These optimization problems are not written here, there is time to fill up later. Next you will write another ES6 implementation of the image lazy loading api--" IntersectionObserver
", this API to achieve better performance.
Native JS implementation picture lazy Loading one: Element.getboundingclientrect ()