1. Why is lazy loading needed?
For usage scenarios with too many pictures, in order to increase the page loading speed and improve the user experience, we do not load pictures that do not appear within the field of view. , wait until it appears in the field of view before loading.
2. The implementation principle of lazy loading
-The implementation principle is very simple. First, point the src of img to a small picture, and store the real address of the picture in img. In a custom attribute,
, wait until the image appears within the field of view, get the img element, and change src The value in is assigned to src.
3. Knowledge points necessary to implement lazy loading
(1) Obtain the window, window scrolling and offset height of the element from the top of the window, and calculate whether the element appears within the visible range of the window ;

Paste_Image.png
1 2 3 4 5 6 7 8 9 10 | function isShow( $el ){
var winH = $(window).height(),
scrollH = $(window).scrollTop(),
top = $el .offset().top;
if (top < scrollH + winH){
return true;
} else {
return false;
}
}
|
Copy after login
(2) Listen to the window scrolling event and check whether the element is within the visible range Inside;
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | $(window).on( 'scroll' , function (){
checkShow();
})
checkShow();
function checkShow(){
$( 'img' ).each( function (){
var $cur = $(this);
if (!!isloaded( $cur )){ return ;}
if (isShow( $cur )) {
setTimeout( function (){
showImg( $cur );
},300)
};
});
}
|
Copy after login
(3) When the element is displayed, replace the previous default photo with the photo in src.
1 2 3 4 | function showImg( $el ){
$el .attr( 'src' , $el .attr( 'src' ));
$cur .data( 'isloaded' ,true);
}
|
Copy after login

Paste_Image.png

Paste_Image.png
The above is the detailed content of Describe in detail how jQuery implements lazy loading. For more information, please follow other related articles on the PHP Chinese website!