1.什麼是懶加載
當圖片出現在可視區域時才加載圖片。
2.懶加載實現方式
核心:可視區域(clientHeight)+滾動條距離頂部高度(scrollTop) > 元素到頂部距離(offsetTop)
0.獲取元素到頂部的距離(offsetTop)
1.監聽滾動
2.在滾動方法裏,實時獲取可視區域(clientHeight) 和 滾動條距離頂部高度(scrollTop)
3.對單個img進行懶加載
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<style type="text/css">
body{
margin: 0px;
}
</style>
</head>
<body>
<div style="width: 100px;height: 100px;margin-top: 1200px;">
<img data-src="img01.png" width="100px" height="100px" style="margin-top: 1200px;" id="img01"/>
</div>
<script type="text/javascript">
var img01=document.getElementById('img01');
window.onscroll=function () {
//元素距離頂部的高度
var oHeight=img01.offsetTop;
//可視區域
var height=document.documentElement.clientHeight;
//滾動條距離頂部高度
var scrollTop=document.documentElement.scrollTop||document.body.scrollTop;
if (height+scrollTop>oHeight) {
img01.src=img01.getAttribute("data-src");
}
}
</script>
</body>
</html>
4.對多個標籤進行懶加載
在需要懶加載的img標籤的class屬性添加上“lazyLoad”
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<style type="text/css">
body{
margin: 0px;
}
</style>
</head>
<body>
<div style="width: 100px;height: 100px;margin-top: 100px;">
<img data-src="img01.png" width="100px" height="100px" style="margin-top: 1px;" class="lazyLoad"/>
</div>
<div style="width: 100px;height: 100px;margin-top: 300px;">
<img data-src="img01.png" width="100px" height="100px" style="margin-top: 1px;" class="lazyLoad"/>
</div>
<div style="width: 100px;height: 100px;margin-top: 300px;">
<img data-src="img01.png" width="100px" height="100px" style="margin-top: 1px;" class="lazyLoad"/>
</div>
<div style="width: 100px;height: 100px;margin-top: 300px;">
<img data-src="img01.png" width="100px" height="100px" style="margin-top: 1px;" class="lazyLoad"/>
</div>
<script type="text/javascript">
var imgArray=document.getElementsByClassName("lazyLoad");
var len=imgArray.length;
for (var i = 0; i < len; i++) {
var oHeight=imgArray[i].offsetTop;
//可視區域
var height=document.documentElement.clientHeight;
if (oHeight<height) {
imgArray[i].src=imgArray[i].getAttribute("data-src");
}
}
window.onscroll=function(){
for (var i = 0; i < len; i++) {
var oHeight=imgArray[i].offsetTop;
//可視區域
var height=document.documentElement.clientHeight;
//滾動條距離頂部高度
var scrollTop=document.documentElement.scrollTop||document.body.scrollTop;
if (height+scrollTop>oHeight) {
if (imgArray[i].src=="") {
imgArray[i].src=imgArray[i].getAttribute("data-src");
}
}
}
};
</script>
</body>
</html>