图片懒加载
<div class="container"> <img src="loading.gif" data-src="pic.png"> <img src="loading.gif" data-src="pic.png"> <img src="loading.gif" data-src="pic.png"> <img src="loading.gif" data-src="pic.png"> <img src="loading.gif" data-src="pic.png"> <div> <script> // 获取全部的图片元素 let imgs = document.querySelectorAll('img') function lazyLoad () { // 获取浏览器滚动的过的距离 var scrollTop = document.body.scrollTop || document.documentElement.scrollTop // 获取浏览器可视区的高度 var winHeight = window.innerHeight for (let i = 0; i < imgs.length; i++) { // 判断是否满足图片加载条件 if (imgs[i].offsetTop < scrollTop + winHeight) { imgs[i].src = imgs[i].getAttribute('data-src') } } } window.onscroll = lazyLoad() </script>