一、总结
一句话总结:
到达指定加载图片位置时,用data-src的属性值替换img的src的属性值即可,这个时候img就会去请求资源
imgs[i].src = imgs[i].getAttribute('data-src');
二、图片懒加载原理
1 <!DOCTYPE html>
2 <html lang="en">
3 <head>
4 <meta charset="UTF-8">
5 <meta name="viewport" content="width=device-width, initial-scale=1.0">
6 <meta http-equiv="X-UA-Compatible" content="ie=edge">
7 <title>图片懒加载</title>
8 <style>
9 img {
10 display: block;
11 width: 100%;
12 height: 300px;
13 margin-bottom: 20px;
14 }
15 </style>
16 </head>
17 <body>
18 <img data-src="./images/1.jpg" alt="">
19 <img data-src="./images/2.jpg" alt="">
20 <img data-src="./images/3.jpg" alt="">
21 <img data-src="./images/4.jpg" alt="">
22 <img data-src="./images/5.jpg" alt="">
23 <img data-src="./images/6.jpg" alt="">
24 <img data-src="./images/7.jpg" alt="">
25 <img data-src="./images/8.jpg" alt="">
26 <img data-src="./images/9.jpg" alt="">
27 <img data-src="./images/10.jpg" alt="">
28 <img data-src="./images/1.jpg" alt="">
29 <img data-src="./images/2.jpg" alt="">
30 </body>
31 <script>
32 var imgs = document.querySelectorAll('img');
33
34 //offsetTop是元素与offsetParent的距离,循环获取直到页面顶部
35 function getTop(e) {
36 var T = e.offsetTop;
37 while(e = e.offsetParent) {
38 T += e.offsetTop;
39 }
40 return T;
41 }
42
43 function lazyLoad(imgs) {
44 var H = document.documentElement.clientHeight;//获取可视区域高度
45 var S = document.documentElement.scrollTop || document.body.scrollTop;
46 for (var i = 0; i < imgs.length; i++) {
47 if (H + S > getTop(imgs[i])) {
48 imgs[i].src = imgs[i].getAttribute('data-src');
49 }
50 }
51 }
52
53 window.onload = window.onscroll = function () { //onscroll()在滚动条滚动的时候触发
54 lazyLoad(imgs);
55 }
56 </script>
57 </html>