性能优化案例之懒加载
<!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> </head> <body> <img src="./loading.gif" data-src="./img1.jpg" alt="" height="300"> <img src="./loading.gif" data-src="./img1.jpg" alt="" height="300"> <img src="./loading.gif" data-src="./img1.jpg" alt="" height="300"> <img src="./loading.gif" data-src="./img1.jpg" alt=""> <img src="./loading.gif" data-src="./img1.jpg" alt=""> <img src="./loading.gif" data-src="./img1.jpg" alt=""> <img src="./loading.gif" data-src="./img1.jpg" alt=""> <img src="./loading.gif" data-src="./img1.jpg" alt=""> <img src="./loading.gif" data-src="./img1.jpg" alt=""> <img src="./loading.gif" data-src="./img1.jpg" alt=""> <img src="./loading.gif" data-src="./img1.jpg" alt=""> <script> const img = document.getElementsByTagName('img'); const len = img.length let n = 0; const lazyLoad = ()=>{ let {clientHeight} = document.documentElement let scrollTop = document.documentElement.scrollTop || document.body.scrollTop for(let i = n ; i<len ; i++){ console.log(img[i].offsetTop) if(img[i].offsetTop < clientHeight+scrollTop ){ img[i].src = img[i].getAttribute("data-src") n = i+1 } } } lazyLoad() window.onscroll = lazyLoad </script> </body> </html>