Javascript 在移动设备上延迟加载图像
我正在使用这个延迟加载代码 JS代码:Javascript 在移动设备上延迟加载图像,javascript,jquery,lazy-loading,jquery-lazyload,Javascript,Jquery,Lazy Loading,Jquery Lazyload,我正在使用这个延迟加载代码 JS代码: $(window).on('scroll touchmove', function(){ if( $('.touch').length) { var images = $('.theme-slider img[data-lazy]'); images.each(function(index){ if(isElementVisible(this)) { $(this).attr('src', $(t
$(window).on('scroll touchmove', function(){
if( $('.touch').length) {
var images = $('.theme-slider img[data-lazy]');
images.each(function(index){
if(isElementVisible(this)) {
$(this).attr('src', $(this).attr('data-lazy'));
$(this).removeAttr('data-lazy');
}
})
if(images.length == 0) {
$(window).off('scroll touchmove');
}
}
});
// Checking if an image is within the viewport
function isElementVisible(el){
var rect = el.getBoundingClientRect();
return (
rect.top >= 0 &&
rect.left >= 0 &&
rect.bottom <= (window.innerHeight) &&
rect.right <= (window.innerWidth)
);
}
$(窗口).on('scroll touchmove',function(){
如果($('.touch').length){
var images=$('.theme slider img[data lazy]');
图像。每个(函数(索引){
如果(isElementVisible(此)){
$(this.attr('src',$(this.attr('data-lazy'));
$(this.removeAttr('data-lazy');
}
})
如果(images.length==0){
$(窗口).off('滚动触摸移动');
}
}
});
//检查图像是否在视口中
函数isElementVisible(el){
var rect=el.getBoundingClientRect();
返回(
rect.top>=0&&
rect.left>=0&&
我建议在jQuery中使用rect.bottom