1、在img元素上绑定一个属性data-src,放上图片真实的地址,src可以放一个占位图或者为空。
2、当图片进入可视区域的时候,将data-src值赋值给src。
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<!--适应移动端-->
<meta name="viewport" content="width=device-width, initial-scale=1">
<!--css样式-->
<style>
body{background-color: #EBEBEB}
.aaa{background-color: #CB4F51;padding: 10px;display: block}
img {
background: #F1F1FA;
width: 375px;
height: 450px;
display: block;
margin: 10px auto;
border: 0;
}
</style>
</head>
<body>
<div>
<img data-src="https://dss3.bdstatic.com/70cFv8Sh_Q1YnxGkpoWK1HF6hhy/it/u=2534506313,1688529724&fm=26&gp=0.jpg" />
<img data-src="https://media-coa.feihe.com/coa/0/db0080e0-96cb-4eee-a5b3-ca0fdbf9bda6.png" />
<img data-src="https://dss0.bdstatic.com/70cFvHSh_Q1YnxGkpoWK1HF6hhy/it/u=151472226,3497652000&fm=26&gp=0.jpg" />
<img data-src="https://dss1.bdstatic.com/70cFuXSh_Q1YnxGkpoWK1HF6hhy/it/u=3892521478,1695688217&fm=26&gp=0.jpg" />
<img data-src="https://dss0.bdstatic.com/70cFuHSh_Q1YnxGkpoWK1HF6hhy/it/u=1906469856,4113625838&fm=26&gp=0.jpg" />
<img data-src="https://dss1.bdstatic.com/70cFvXSh_Q1YnxGkpoWK1HF6hhy/it/u=1776601493,3966748998&fm=26&gp=0.jpg" />
</div>
<script type="text/javascript">
document.addEventListener("DOMContentLoaded", function() {
var imgs = document.querySelectorAll('img');
function throttle(func, wait) {
var timer = null;
return function (...args) {
if (!timer) {
func(...args);
timer = setTimeout(() => {
timer = null;
}, wait);
}
};
}
// 方法1: H + S > offsetTop
// 1. offsetTop:元素到offsetParent顶部的距离
// 2. offsetParent:距离元素最近的一个具有定位的祖宗元素(relative,absolute,fixed),若祖宗都不符合条件,offsetParent为body。
function lazyLoad1(imgs) {
// function getTop(e) {
// var T = e.offsetTop;
// while ((e = e.offsetParent)) {
// T += e.offsetTop;
// }
// return T;
// }
var H = document.documentElement.clientHeight;
var S = document.documentElement.scrollTop || document.body.scrollTop;
imgs.forEach(function (img) {
if (H + S + 100 > img.offsetTop && !img.src) {
img.src = img.dataset.src;
}
});
}
var throttleLazyLoad1 = throttle(lazyLoad1, 200);
// 方法2 el.getBoundingClientRect().top <= window.innerHeight
function lazyLoad2(imgs) {
function isIn(el) {
var bound = el.getBoundingClientRect();
var clientHeight = window.innerHeight;
return bound.top <= clientHeight + 100;
}
Array.from(imgs).forEach(function (img) {
if (isIn(img) && !img.src) {
img.src = img.dataset.src;
}
});
}
var throttleLazyLoad2 = throttle(lazyLoad2, 200);
// 调用方法1和2
window.onload = window.onscroll = function() {
throttleLazyLoad1(imgs);
// throttleLazyLoad2(imgs);
}
// 方法3:IntersectionObserver(IE不支持)
function lazyLoad3(imgs) {
const io = new IntersectionObserver(
(changes) => {
changes.forEach((change) => {
var img = change.target;
// intersectionRatio 完全可见时为1
if (change.intersectionRatio > 0 ) {
if (!img.src){
img.src = img.dataset.src;
}
}
img.onload = img.onerror = () => io.unobserve(img);
})
}
)
imgs.forEach((img) => io.observe(img))
}
// lazyLoad3(imgs);
});
</script>
</body>
</html>