原生js实现懒加载
原理:
让img的src为空,图片的真实地址可以存储在img一个自定义的属性里,就比如date-src吧,等到目标图片出现在视野了,把data-src里的值赋给src
实现懒加载必备知识:
用getAttribute(属性名)获取自定义属性
除此之外,我们还需要知道clientHeight、offsetHeight、scrollHeight、offsetTop、scrollTop的区别以及所代表的含义
<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><meta http-equiv="X-UA-Compatible" content="ie=edge"><title>图片懒加载</title><style>*{margin: 0;padding: 0;}img{display: block;width: 400px;height: 300px;}</style></head><body><img src="" date-src="../images/1.jpg" date-h="300" alt=""><img src="" date-src="../images/2.jpg" date-h="300" alt=""><img src="" date-src="../images/3.jpg" date-h="300" alt=""><img src="" date-src="../images/4.jpg" date-h="300" alt=""><img src="" date-src="../images/5.jpg" date-h="300" alt=""><img src="" date-src="../images/bird.png" alt=""><script>var imgs=document.getElementsByTagName("img");var n=0;//用来记录当前是第几张图片var seeHeight = document.documentElement.clientHeight;var h = imgs[0].getAttribute('date-h');// console.log(h);var index = Math.floor(seeHeight/h);//一进页面展示的几张图片for(i=0;i<=index;i++){imgs[i].src = imgs[i].getAttribute('date-src');}window.onscroll = function(){for (var i = n; i < imgs.length; i++) {var scrollTop = document.body.scrollTop || document.documentElement.scrollTop;if (imgs[i].offsetTop < seeHeight + scrollTop) {if (imgs[i].getAttribute('src') == '') {imgs[i].src = imgs[i].getAttribute('date-src');}n = i + 1;console.log('n = ' + n);}}}</script></body></html>