<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>LozyLoad</title>
<style>
.images{
display: flex;
flex-direction: column;
text-align: center;
500px;
}
.img-item{
height:400px;
400px;
margin: 20px;
}
</style>
</head>
<body>
<div class="images">
<img class="img-item" alt="loading" data-src="imgs/img01.jpg">
<img class="img-item" alt="loading" data-src="imgs/img02.jpg">
<img class="img-item" alt="loading" data-src="imgs/img03.jpeg">
<img class="img-item" alt="loading" data-src="imgs/img04.jpg">
<img class="img-item" alt="loading" data-src="imgs/img02.jpg">
</div>
<!--
<script type="text/javascript">
//获取观察器实例 changes是被观察的对象数组
var observer = new IntersectionObserver(function(changes){
console.log(changes);
changes.forEach(function(index,item){
if(item.intersectionRatio > 0 && item.intersectionRatio < 1)
//target:被观察的目标元素,是一个 DOM 节点对象
item.target.src = item.target.dataset.src;
});
});
function addObserver(){
var listItems = document.querySelectorAll('.img-item');
listItems.forEach(function(item){
//实例的observe方法可以指定观察哪个DOM节点
//开始观察 observe的参数是一个 DOM 节点对象
observer.observe(item);
});
}
addObserver();
</script>
-->
<script type="text/javascript">
//获取img
var imgs = document.querySelectorAll('img');
//懒加载方法
var lazyload = function(){
//获取浏览器滚动高度
var scrollTop = document.body.scrollTop || document.documentElement.scrollTop;
//获取浏览器可视高度
var winTop = window.innerHeight;
for(var i=0;i < imgs.length;i++){
//imgs[i].offsetTop 距离文档顶部的高度
//如果元素距离文档顶部的高度小于 浏览器的滚动高度加浏览器的可视高度,则需要加载
if(imgs[i].offsetTop < scrollTop + winTop ){
imgs[i].src = imgs[i].getAttribute('data-src');
}
}
}
//调用懒加载函数
function throttle(method,delay){
var timer = null;
return function(){
var context = this, args=arguments;
clearTimeout(timer);
timer=setTimeout(function(){
// method.apply(context,args);
method()
},delay);
}
}
window.onscroll = throttle(lazyload,200);
</script>
</body>
</html>