当前位置: 移动技术网 > IT编程>开发语言>JavaScript > 原生js实现图片懒加载+加入节流

原生js实现图片懒加载+加入节流

2019年08月08日  | 移动技术网IT编程  | 我要评论

这两天在学习图片的懒加载实现,看了很多大佬的博客,终于有了点成果。现在用了其中一位大佬的文章中的代码实现了图片懒加载并且在其基础上加入了节流函数。

原理就不多讲了,有需要的可以去大佬的文章看看。大佬文章可以从这里进->(https://www.jianshu.com/p/9b30b03f56c2)。

先上html结构:

1     <div></div>
2     <img src="" id="i1" data-src="image1">
3     <div></div>
4     <img src="" id="i2" alt="" data-src="image2">

然后是样式:

 1 <style>
 2         * {
 3             padding: 0;
 4             margin: 0;
 5         }
 6 
 7         div {
 8             height: 2000px;
 9         }
10 
11         #i1 {
12             display: block;
13             width: 200px;
14             height: 200px;
15             background-color: red;
16         }
17 
18         #i2 {
19             display: block;
20             width: 200px;
21             height: 200px;
22             background-color: green;
23         }
24     </style>

最后是javascript的代码:

 1 <script>
 2         var lasttime = new date().gettime();
 3         function lazyload() {
 4             //放入节流函数前的准备工作
 5             function prework() {
 6                 //获取页面图片标签
 7                 var imgs = document.queryselectorall("img");
 8                 //可视区高度
 9                 var h = window.innerheight || document.documentelement.clientheight || document.body.clientheight;
10 
11                 [].foreach.call(imgs,function (img) {
12                     //判断data-src属性是否存在,不存在代表图片已经加载过
13                     if (!img.getattribute('data-src')) {
14                         return;
15                     }
16                     //判断高度差,替换路径后移除data-src属性
17                     if (img.getboundingclientrect().top < h) {
18                         img.src = img.getattribute('data-src');
19                         img.removeattribute('data-src');
20                     }
21                 });
22 
23                 //利用与运算,如果与前面为false,则不运行后面的语句;若为true,继续运行后面的语句。从而达到路径替换完后可以执行移除监听事件的效果
24                 [].every.call(imgs, function (img) {
25                     return !img.getattribute('data-src');
26                 }) && (window.removeeventlistener("scroll", lazyload));
27             }
28 
29             //节流函数
30             function throttle() {
31                 var nowtime = new date().gettime();
32                 if (nowtime - lasttime > 1000) {
33                     prework();
34                     console.log("节流执行");
35                     lasttime = nowtime;
36                 }
37 
38             }
39 
40             //执行节流函数
41             throttle();
42         }
43 
44         window.addeventlistener("scroll", lazyload);
45         window.addeventlistener("load", lazyload);
46 
47     </script>

js的代码里面加了一些注释,希望能帮助大家理解。

本人是前端小菜鸟一枚,代码里如果出现错误希望大家多多包涵并在评论区提出,本人会认真改正的!

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网