<script type="text/javascript"> // 懒加载 // getBoundClientRect 的实现方式 let imgList = [...document.querySelectorAll('img')] let num = imgList.length let lazyLoad = (function (){ let count = 0 return function (){ let deleteIndexList = [] imgList.forEach((img, index) => { console.log(img) let rect = img.getBoundingClientRect() if(rect.top < window.innerHeight){ img.src = img.dataset.src deleteIndexList.push(index) count++ if(count === num){ document.removeEventListener('scroll', lazyLoad) } } }) imgList = imgList.filter((_, index) => !deleteIndexList.includes(index)) } })() // intersectionObserver 的实现方式 let imgList = [...document.querySelectorAll('img')] let lazyLoad = (function (){ let observer = new IntersectionObserver(entries => { entries.forEach(entry => { if(entry.intersectionRatio > 0){ entry.target.src = entry.target.dataset.src observer.unobserve(entry.target) } }) }) imgList.forEach(img => { observer.observe(img) }) })() </script>