原理:
IntersectionObserver.observe():使IntersectionObserver开始监听一个目标元素;
isIntersecting属性:可以判断该元素是否出现在视口内;
遍历每个img元素,然后监听每一个元素,最后根据isIntersecting属性去判断元素是否出现在视口内,从而决定是否让他加载。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
img {
height: 450px;
display: block;
margin-bottom: 20px;
}
</style>
</head>
<body>
<!--图片地址暂时先保存在data-src这个自定义属性上面-->
<img data-src="./img-loop/img/1.jpg" alt="懒加载1" />
<img data-src="./img-loop/img/2.png"