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.
-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.
function isShow($el){ var winH = $(window).height(),//获取窗口高度 scrollH = $(window).scrollTop(),//获取窗口滚动高度 top = $el.offset().top;//获取元素距离窗口顶部偏移高度 if(top < scrollH + winH){ return true;//在可视范围 }else{ return false;//不在可视范围 } }
$(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)//设置时间是为了更好的看出效果 }; }); }
function showImg($el){ $el.attr('src', $el.attr('src')); $cur.data('isloaded',true); }
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!