📖网站优化:JS实现图片懒加载

前言

用 JS 写了一个简单的图片懒加载

HTML代码

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>懒加载</title>
</head>
<body>
	<div class="imglist">
		<li><img class="src_img" src="lgin.gif" data-src="http://picnew8.photophoto.cn/20140808/qidanchetupian-10092067_1.jpg"></li>
		<li><img class="src_img" src="lgin.gif" data-src="http://picnew10.photophoto.cn/20160527/qidanchetupian-25295289_1.jpg"></li>
		<li><img class="src_img" src="lgin.gif" data-src="http://img95.699pic.com/xsj/1f/2f/pl.jpg!/fw/700/watermark/url/L3hzai93YXRlcl9kZXRhaWwyLnBuZw/align/southeast"></li>
		<li><img class="src_img" src="lgin.gif" data-src="http://picnew8.photophoto.cn/20140808/qidanchetupian-10092068_1.jpg"></li>
		<li><img class="src_img" src="lgin.gif" data-src="https://picnew7.photophoto.cn/20121225/qidanchetupian-09180972_1.jpg"></li>
		<li><img class="src_img" src="lgin.gif" data-src="http://picnew8.photophoto.cn/20140808/qidanchetupian-10092063_1.jpg"></li>
		<li><img class="src_img" src="lgin.gif" data-src="http://pic47.photophoto.cn/20180608/0006018936446767_b.jpg"></li>
	</div>
<script type="text/javascript" src="load_js.js"></script>
</body>
</html>

JS 代码 load_js.js

window.onload = function(){
	// 获取到该class的所有图片
	var imgs = document.querySelectorAll('.src_img');
	// 获取到浏览器顶部的距离
	function getTop(e){
		return e.offsetTop;
	}
	// 懒加载函数
	function lanjia(imgs){
		// 可视区域高度
		var h = window.innerHeight;
		//滚动区域高度
		var s = document.documentElement.scrollTop || document.body.scrollTop;
		for(var i=0;i<imgs.length;i++){
			//当图片距离顶部的距离大于可视区域和滚动区域之和时执行懒加载
			if ((h+s)>getTop(imgs[i])) {
				(function(i){
					imgs[i].src = imgs[i].getAttribute('data-src')
				})(i)
			}
		}
	}
	lanjia(imgs);
	window.onscroll =function(){
		lanjia(imgs);
	}
}

标签

🧐发表评论

您必须启用javascript才能在此处查看验证码