懒加载的基本逻辑就是在网页没有在视窗中出现的地方的图片等数据可以暂时不需要加载,提高网页载入速度和用户体验,等待图片出现在视窗中时,再去进行加载。
下面是如何判断div是否出现在视窗中
源码:
<div class="see"></div>
<script>
var div=(function(){
function see(p){
$nodeH=p.height();
$nodeoffset=p.offset().top;
$windowH=$(window).height();
$scrollTop=$(window).scrollTop();
if($nodeoffset<$windowH+$scrollTop&&$nodeoffset+$nodeH>$scrollTop){
console.log('see');
//p.data('issee', true);
}
else{
console.log('cant find it');
}
}
function scroll(p){
$(window).on('scroll', function(){
//有时已经加载的图片不需要再去判断是否需要加载
//if(p.data('issee')){return}
see(p);
})
}
return {
scroll:scroll
}
})()
div.scroll($('.see'));
</script>
样列
预览:
https://jirengu-inc.github.io/jrg-renwu8/homework/%E5%BC%A0%E8%BD%A9/renwu29-2.html
源码:
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<script src='http://apps.bdimg.com/libs/jquery/2.1.4/jquery.min.js'></script>
<style>
.full{
height: 6000px;
}
.pic{
width:1080px;
height: 1080px;
}
</style>
</head>
<body>
<div class="full">
![](C:\Users\Administrator\Desktop\lazyload\1.jpg)
![](C:\Users\Administrator\Desktop\lazyload\2.jpg)
![](C:\Users\Administrator\Desktop\lazyload\3.jpg)
![](C:\Users\Administrator\Desktop\lazyload\4.jpg)
![](C:\Users\Administrator\Desktop\lazyload\5.jpg)
![](C:\Users\Administrator\Desktop\lazyload\6.jpg)
![](C:\Users\Administrator\Desktop\lazyload\7.jpg)
![](C:\Users\Administrator\Desktop\lazyload\8.jpg)
![](C:\Users\Administrator\Desktop\lazyload\9.jpg)
</div>
<script>
var zhangxuan=(function(){
function showimg(p){
p.attr('src', p.attr('data-src'));
p.data('isload', true);
}
function isimg(node){
node.each(function(){
var $node=$(this),
$dscrollTop=$(document).scrollTop(),
$wwidth=$(window).height(),
$picoffsetTop=$node.offset().top;
if(!!$node.data('isload')){ //优化已加载图片不执行
return
}
else{
if(($dscrollTop+$wwidth)>=$picoffsetTop){
showimg($node);
}
}
})
}
function bind(node){
var clock;
$(window).on('scroll', function(){
if(clock){
clearTimeout(clock);
}
clock=setTimeout(function(){ //优化滚轮停止时才执行
isimg(node);
}, 300)
})
// $(window).on('scroll', function(){
// isimg(node);
// console.log(1);
// })
}
return{
bind:bind
}
})()
zhangxuan.bind($('.pic'));
</script>
</body>
</html>