JavaScript 懒加载
懒加载,顾名思义,就是不急慢慢来,等迫不得已的时候再加载;
- 在网页刚打开时,很可能因为请求太多而一时拥塞,并且习惯性的在body后有JavaScript脚本,这样一来就容易发生页面卡顿或崩溃等问题;所以我们可以采取动态加载的方式来让请求变得稀疏;
原理:
- 浏览器遇到src属性会阻塞渲染树,先下载内容,如果是脚本的话还会运行;
- 先将img标签中的src链接设为同一张图片(空白图片),将其真正的图片地址存储再img标签的自定义属性中(比如data-src)。当js监听到该图片元素进入可视窗口时,即将自定义属性中的地址存储到src属性中,达到懒加载的效果。
关键问题:
- 什么时候加载
- 如何加载
- 怎样持续的动态加载
为了解决上述问题,我们不妨思考,我们什么时候需要加载——> 当图片显示在屏幕内时;那什么情况会改变屏幕的位置呢----->当然是滚动条滑动的时候
首先是HTML的DOM
<!DOCTYPE html>
<html>
<head>
<meta content="text/html;charset=utf-8" /><title>LazyLoad</title>
<style>
body {text-align: center;}
.list {margin-bottom: 40px;}
</style>
</head>
<body>
<h1>LazyLoad</h1>
<div id="content">
<img src="" data-src="1.jpg" width="1000" height="600">
<img src="" data-src="1.jpg" width="1000" height="600">
<img src="" data-src="1.jpg" width="1000" height="600">
<img src="" data-src="1.jpg" width="1000" height="600">
<img src="" data-src="1.jpg" width="1000" height="600">
<img src="" data-src="1.jpg" width="1000" height="600">
<img src="" data-src="1.jpg" width="1000" height="600">
<img src="" data-src="1.jpg" width="1000" height="600">
<img src="" data-src="1.jpg" width="1000" height="600">
<img src="" data-src="1.jpg" width="1000" height="600">
<img src="" data-src="1.jpg" width="1000" height="600">
</div>
<script type="text/javascript">
var imgs = document.images;
function show(){
var winH = (document.compatMode=="CSS1Compat")?document.documentElement.clientHeight
:document.body.clientHeight;
var cnt = imgs.length;
console.log(cnt);
if(!cnt) return false;
console.log(1);
for (var i = 0; i < cnt; i++) {
var o = imgs[i];
var top = o.getBoundingClientRect().top;
var bottom = o.getBoundingClientRect().bottom;
console.log(top,winH,bottom);
if((top>0&&top<winH)||(bottom>0&&bottom<winH))
{
o.setAttribute('src',o.getAttribute('data-src'));
}
}
}
window.onscroll = function(){
setTimeout(function(){show()},1000);
}
show();
</script>
</body>
</html>
注意这里的clientHeight是当前窗口大小(不包含scroll)而getBoundClientRect()是所有元素的相对位置,包含top right bottom left,表示元素到当前窗口各边的距离;
完整的判断为,元素的上下左右只要有一个边在窗口内,就可以加载;
- 记得要先初始加载;
- 最好将已经加载的移除队列