处理方案:
- 把所有需要延迟加载的图片用一个盒子包起来,设置宽高和默认占位图
- 开始把所有img的scr为空,把真实图片的地址放到img的自定义属性上,让img隐藏
- 等到所有其它资源都加载完成后,我们再开始加载图片
- 对于很多图片,需要当页面滚动的时候,当前图片区域完全显示出来之后再加载真实图片
- 浏览器低端距离页面顶端的偏移
- 图片底部距离页面顶端的偏移
<style>
* {
margin: 0px;
padding: 0px;
}
.imgBox {
margin: 0px auto 20px;
width: 800px;
height: 160px;
overflow: hidden;
background: #ccc;
}
.imgBox img {
width: 100%;
display: none;
}
</style>
<body>
<div class="container">
</div>
<script src="./node_modules/jquery/dist/jquery.min.js"></script>
<script src="./index.js"></script>
</body>
</html>
let $imgBox = $('.imgBox'),
$img = $imgBox.children('img');
$(window).on('load scroll',function() {
if( $img.attr('isLoad') === 'true') return;
let A = $imgBox.height() + $imgBox.offset().top,
B = $(this.window).height() + $(window).scrollTop();
if(B >= A) {
$img.attr('src',$img.attr('data-img'));
$img.on('load',function() {
$img.stop().fadeIn();
})
$img.attr('isLoad',true);
}
})
let str = ``;
new Array(20).fill(null).forEach((item,index) => {
str += `<div class="imgBox">
<img src="" data-img="http://www.zhufengpeixun.cn/main/img/banner10.png" />
</div>`
})
let $container = $('.container');
$container.html(str);
let $imgBoxs = $container.children('.imgBox');
$(window).on('load scroll',function() {
let $B = $(window).height() + $(window).scrollTop();
$imgBoxs.each((index,item) => {
let $item = $(item);
let $itemH = $item.height() + $item.offset().top,
$isLoad = $item.attr('isLoad');
if($B >= $itemH && $isLoad !== 'true') {
this.console.log('xxx',index);
$item.attr('isLoad',true);
let $img = $item.children('img');
$img.attr('src',$img.attr('data-img'));
$img.on('load',function() {
$img.stop().fadeIn();
})
}
})
})