This article teaches you how to implement jquery's lazy loading to the top.
How to determine whether an element appears in the visible range of the window (between the upper edge and lower edge of the browser, visible to the naked eye). Write a function isVisible to implement
function isVisible($node){ var winH = $(window).height(), winS = $(window).scrollTop(), nodeHeight = $node.height(), nodeTop = $node.offset().top; if(winH + winS >= nodeTop && winS < nodeTop + nodeHeight){ return true; }else{ return false; } }
When the window scrolls, determine whether an element appears in the visible range of the window. Print true to the console every time it occurs. Use code to implement
function isVisible($node){ $(window).on('scroll',function(){ var winH = $(window).height(), winS = $(window).scrollTop(), nodeHeight = $node.height(), nodeTop = $node.offset().top; if(winH + winS >= nodeTop && winS < nodeTop + nodeHeight ){ console.log(true); }else{ console.log(false); } }); }
isVisible($node);
When the window scrolls, determine whether an element appears in the visible range of the window. Print true on the console when the element appears for the first time, and no processing will be done when it appears again. What is the principle of lazy loading of
function isVisible($node){ $(window).on('scroll',function(){ var winH = $(window).height(), winS = $(window).scrollTop(), nodeHeight = $node.height(), nodeTop = $node.offset().top; if(winH + winS >= nodeTop && winS < nodeTop + nodeHeight ){ if(!$node.attr("data-sc")){ console.log(true); $node.attr("data-sc",true); }else{ return; } }else{ return; } }); } isVisible($node);
images using code?
When the page loads, point the page's img address to a small, identical white image, and put the real image address in the created custom attribute, such as:
<img src="small.png" data-src="true.png">
src is the thumbnail address, data-src is the real address.
When the picture appears in the visible area of the window, assigning the real picture address in the custom attribute to src is the implementation principle of lazy loading.
This article explains jquery. For more related content, please pay attention to the php Chinese website.
Related recommendations:
##JS arrays, strings and mathematical functions
About JS time objects and recursion issues
The above is the detailed content of Implement jquery lazy loading and return to top. For more information, please follow other related articles on the PHP Chinese website!