纯JS实现超简单图片懒加载

懒加载是一种对网页性能优化和节省用户流量的方式,优先显示可视区域的图片而不一次性加载所有图片,当需要显示的时候再发送图片请求,避免打开网页时加载过多资源,当页面中需要一次性载入很多图片的时候,往往都是需要用懒加载

点我——立即在线体验

原理

通过监听浏览器滚动事件及滚动个过程中图片位置,动态为img标签的src属性赋值,废话不多说,直接上干货

全部代码

HTML代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
<!DOCTYPE html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,initial-scale=1.0,maximum-scale=1.0,user-scalable=0"/>
<style type="text/css">
.content{
margin: 0 auto;
text-align: center;
max-width: 640px;
margin-bottom: -18px;
}
.content img{
width: 100%;
display: inherit;
}
.content div.title{
line-height: 1.5em;
margin-bottom: 5px;
}
.copyright{
text-align: center;
margin-top: -35px;
margin-bottom: 10px;
}
a{
text-decoration: none;
}
</style>
<body>
<div id="main-container"></div>
<div class="copyright">版权所有<br/><a href="http://www.cnlod.com">北京大医同盟健康管理有限责任公司</a></div>
</body>
<script src="data.js" type="text/javascript" charset="utf-8"></script>
<script src="image-lazyload.js" type="text/javascript" charset="utf-8"></script>
</html>

核心JS(image-lazyload.js)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
window.Andy = (function(window, document, undefined) {

'use strict';

var store = [],
offset,
throttle,
poll;

/**
* 自定义图片进入视野规则
* @param {Object} el 待处理单张图片
*/
var imageInView = function(el) {
var coords = el.getBoundingClientRect(); //关键方法:获取图片视口位置
return ((coords.top >= 0 && coords.left >= 0 && coords.top) <= (window.innerHeight || document.documentElement.clientHeight) + parseInt(offset));
};

/**
* 滚动监听处理
*/
var pagePolling = function() {
for (var i = store.length; i--;) {
var self = store[i];
if (imageInView(self)) {
self.src = self.getAttribute('data-andy');
store.splice(i, 1);
}
}
};

var eventProcess = function() {
clearTimeout(poll);
poll = setTimeout(pagePolling, throttle);
};

/**
* 功能初始化,事件注入
* @param {Object} obj 初始化参数对象
*/
var globalInit = function(obj) {
var nodes = document.querySelectorAll('[data-andy]');
var opts = obj || {};
offset = opts.offset || 0;
throttle = opts.throttle || 250;

for (var i = 0; i < nodes.length; i++) {
store.push(nodes[i]);
}

eventProcess();

if (document.addEventListener) {
window.addEventListener('scroll', eventProcess, false);
} else {
window.attachEvent('onscroll', eventProcess);
}
};

return {
init: globalInit
};

})(window, document);

Andy.init({
offset: 0,//设置离可视区域多少像素时执行图片加载
throttle: 0 //图片延时多少毫秒加载
});

测试数据(data.js)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
var doctors = [{
"doctorName": "大医明鉴,专家有话说",
"title": "健康之路,大医相伴!",
"link": "http://dwz.cn/7dFc9b",
"img": "http://audio.cnlod.com/images/dayimingjian.jpg"
},{
"doctorName": "赵宇红",
"title": "『大医同盟·公益讲堂』拉肚子?腹泻?教你辨别“真假”",
"link": "http://mp.weixin.qq.com/s/4PmP54dPaGXeCenkNzLB1g",
"img": "http://audio.cnlod.com/weijiangtang/images/zhaoyuhong.jpg"
}, {
"doctorName": "汪欣",
"title": "『大医同盟·公益讲堂』结直肠癌的治疗没那玄乎?",
"link": "http://mp.weixin.qq.com/s/LmmktEnMt7W1wyiw6JUKkQ",
"img": "http://audio.cnlod.com/weijiangtang/images/wangxin.jpg"
},{
"doctorName": "韩志义",
"title": "『大医同盟·公益微讲堂』雾霾与呼吸",
"link": "http://dwz.cn/5sjs7J",
"img": "http://audio.cnlod.com/weijiangtang/images/hanzhiyi.jpg"
},{
"doctorName": "周炼",
"title": "『大医同盟·公益微讲堂』为什么唇裂术前要正畸?",
"link": "http://dwz.cn/4PW2QT",
"img": "http://audio.cnlod.com/weijiangtang/images/zhoulian.jpg",
},{
"doctorName": "闵宝权",
"title": "『大医同盟·公益微讲堂』负面情绪与躯体化症状",
"link": "http://dwz.cn/4PVECx",
"img": "http://audio.cnlod.com/weijiangtang/images/minbaoquan.jpg",
}, {
"doctorName": "李庆",
"title": "『大医同盟·公益微讲堂』成人心外科常见疾病的治疗现状与发展——冠心病",
"link": "http://dwz.cn/4PWAMp",
"img": "http://audio.cnlod.com/weijiangtang/images/liqing.jpg"
}, {
"doctorName": "王乐今",
"title": "『大医同盟·公益微讲堂』儿童近视的预防与矫正",
"link": "http://dwz.cn/4PWyo4",
"img": "http://audio.cnlod.com/weijiangtang/images/wanglejin.jpg"
}, {
"doctorName": "吕强",
"title": "『大医同盟·公益微讲堂』认清高血压的真面目!",
"link": "http://dwz.cn/4PWuKz",
"img": "http://audio.cnlod.com/weijiangtang/images/lvqiang.jpg"
}, {
"doctorName": "周炜",
"title": "『大医同盟·公益微讲堂』类风湿关节炎的诊断与治疗",
"link": "http://dwz.cn/4PVXq4",
"img": "http://audio.cnlod.com/weijiangtang/images/zhouwei.jpg",
}, {
"doctorName": "张建军",
"title": "『大医同盟·公益微讲堂』如何正确认识心脏早搏",
"link": "http://dwz.cn/4PVYol",
"img": "http://audio.cnlod.com/weijiangtang/images/zhangjianjun.jpg"
}, {
"doctorName": "赵守琴",
"title": "『大医同盟·公益微讲堂』小儿耳聋的处理策略",
"link": " http://dwz.cn/4PVYCA",
"img": "http://audio.cnlod.com/weijiangtang/images/zhaoshouqin.jpg",
}, {
"doctorName": "贾长琪",
"title": "『大医同盟·公益微讲堂』心房颤动的危害与防治",
"link": "http://dwz.cn/4PVZGX",
"img": "http://audio.cnlod.com/weijiangtang/images/jiachangqi.jpg"
}, {
"doctorName": "白文佩",
"title": "『大医同盟·公益微讲堂』月经异常对生育的影响",
"link": "http://dwz.cn/4PVZSK",
"img": "http://audio.cnlod.com/weijiangtang/images/baiwenpei.jpg"
}, {
"doctorName": "王玉琨",
"title": "『大医同盟·公益微讲堂』关注小儿髋关节发育不良,早检查早发现",
"link": "http://dwz.cn/4PW0Di",
"img": "http://audio.cnlod.com/weijiangtang/images/wangyukun.jpg"
}, {
"doctorName": "巩纯秀",
"title": "『大医同盟·公益微讲堂』预防肥胖从娃娃抓起",
"link": "http://dwz.cn/4PW1YE",
"img": "http://audio.cnlod.com/weijiangtang/images/gongchunxiu.jpg"
},{
"doctorName": "赵华安",
"title": "『大医同盟·公益微讲堂』做地球上最专业有爱的团队",
"link": "http://andy.cnlod.com/home.html",
"img": "http://andy.cnlod.com/img/card.png"
}, {
"doctorName": "大医盟",
"title": "『大医同盟·公益微讲堂』轻松找专家",
"link": "https://mp.weixin.qq.com/mp/profile_ext?action=home&__biz=MzIwNTA0ODMyOQ==&scene=123#wechat_redirect",
"img": "http://audio.cnlod.com/images/dayimeng.jpg"
}];

for(index in doctors){
let obj = doctors[index];
let template =
`<div class="content">
<div class="title"><span>${obj.title}——</span><span> ${obj.doctorName}</span></div>
<a href="${obj.link}">
<img data-andy="${obj.img}" src="https://loading.io/spinners/flickr/index.orbit-balls-loading-gif.svg"/></p>
</a>
</div>`;
//document.body.innerHTML+=template;
document.getElementById("main-container").insertAdjacentHTML("afterbegin",template);
}
文章目录
  1. 1. 原理
  2. 2. 全部代码
    1. 2.1. HTML代码
    2. 2.2. 核心JS(image-lazyload.js)
    3. 2.3. 测试数据(data.js)