98JS原生:多图片延迟加载
作者:互联网
有时一个网页很长,如果用户一打开网页,我们就把所有图片给他加载下来,那么如果用户看不到底就关闭了这个网页,那么就会造成性能的浪费。因此,用户下拉到哪个位置,我们就下载到哪个位置,这就是延迟加载。本实例:当图片所在位置的1/3以上暴露在窗口时,才加载这张图片。
```html:run
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
<style>
*{
margin:0;
padding:0;
}
img{
border: none;
}
div{
margin:0 auto;
width: 800px;
height: 400px;
background: url("http://img.pconline.com.cn/images/upload/upc/tx/photoblog/1509/06/c5/12227263_12227263_1441518060703_mthumb.jpg") no-repeat center #e1e1e1;
}
div img{
width: 100%;
height: 100%;
}
p{
width:800px;
height:600px;
line-height:60px;
background: lightgrey;
font-size:30px;
margin:0 auto;
text-indent:13px;
}
</style>
</head>
<body>
<p>需要如下操作,才可以“效果预览”:<br/>(1)点击“效果预览”;<br/>(2)点击“效果预览”正右侧的“对角线箭头图标”;<br/>(3)滚动鼠标滚轮。</p>
</body>
<script>
var data=[
{src:'http://img.pconline.com.cn/images/upload/upc/tx/photoblog/1509/06/c5/12227263_12227263_1441518066203_mthumb.jpg'},
{src:'http://img.pconline.com.cn/images/upload/upc/tx/photoblog/1509/06/c5/12227263_12227263_1441518066203_mthumb.jpg'},
{src:'http://img.pconline.com.cn/images/upload/upc/tx/photoblog/1509/06/c5/12227263_12227263_1441518066203_mthumb.jpg'},
{src:'http://img.pconline.com.cn/images/upload/upc/tx/photoblog/1509/06/c5/12227263_12227263_1441518066203_mthumb.jpg'},
{src:'http://img.pconline.com.cn/images/upload/upc/tx/photoblog/1509/06/c5/12227263_12227263_1441518066203_mthumb.jpg'},
{src:'http://img.pconline.com.cn/images/upload/upc/tx/photoblog/1509/06/c5/12227263_12227263_1441518066203_mthumb.jpg'},
{src:'http://img.pconline.com.cn/images/upload/upc/tx/photoblog/1509/06/c5/12227263_12227263_1441518066203_mthumb.jpg'},
{src:'http://img.pconline.com.cn/images/upload/upc/tx/photoblog/1509/06/c5/12227263_12227263_1441518066203_mthumb.jpg'},
{src:'http://img.pconline.com.cn/images/upload/upc/tx/photoblog/1509/06/c5/12227263_12227263_1441518066203_mthumb.jpg'}
];
var aDiv=document.getElementsByTagName('div');
var aImg=document.getElementsByTagName('img');
function bind(){
var frg=document.createDocumentFragment();
for(var i=0;i<data.length;i++){
var div=document.createElement("div");
div.innerHTML="<img realImg='"+data[i].src+"' alt=''/>";
frg.appendChild(div);
}
document.body.appendChild(frg);
frg=null;
}
bind();
window.onscroll=function(){
var scrollBottom=document.documentElement.scrollTop||document.body.scrollTop+
document.documentElement.clientHeight||document.body.clientHeight;
for(var i=0; i<aDiv.length; i++){
var imgPosition=aDiv[i].offsetTop+aDiv[i].offsetHeight/5;
if(imgPosition<scrollBottom){
aImg[i].src=aImg[i].getAttribute('realImg');
}
}
};
</script>
</html>
```
标签:原生,img,tx,upc,98JS,12227263,upload,mthumb,加载 来源: https://www.cnblogs.com/gushixianqiancheng/p/10967200.html