javascript实现图片延迟加载方法汇总(三种方法)
看到一些大型网站,页面如果有很多图片的时候,当你滚动到相应的行时,当前行的图片才即时加载的,这样子的话页面在打开只加可视区域的图片,而其它隐藏的图片则不加载,一定程序上加快了页面加载的速度,对于比较长的页面来说,这个方案是比较好的。原理是这样:页面可见区域以下的图片先不加载,等到用户向下滚动到图片位置时,再进行加载。这样做的好处在哪里?——当页面有好几屏内容时,有可能用户只看前几屏的内容,这样我们就可以只加载用户需要看的图片,减少服务器向用户浏览器发送图片文件所产生的负荷,下面通过三种方法给大家介绍js实现图片延时加载。
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
|
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" > <html> <head> <title>lazyImage2.html</title> <meta http-equiv= "keywords" content= "keyword1,keyword2,keyword3" > <meta http-equiv= "description" content= "this is my page" > <meta http-equiv= "content-type" content= "text/html; charset=UTF-8" > <!--<link rel= "stylesheet" type= "text/css" href= "./styles.css" mce_href= "styles.css" >--> </head> <body style= "text-align:center" mce_style= "text-align:center" > <p> </p><p> </p><p> </p><p> </p><p> </p> <div style= "height:1290px;width:800px;border:1px;background:gray;" ></div> <div style= "height:150px;width:800px;border:1px;background:green;" ></div> <img class= "lazy" src= "images/sprite.gif" mce_src= "images/sprite.gif" alt= "images/lazyloadImg.jpg" /> <script type= "text/javascript" ><!-- var temp = -1; //用来判断是否是向下滚动(向上滚动就不需要判断延迟加载图片了) window.onscroll = function () { var imgElements = document.getElementsByTagName( "img" ); var lazyImgArr = new Array(); var j = 0; for ( var i=0; i<imgElements.length; i++) { if (imgElements[i].className == "lazy" ){ lazyImgArr[j++] = imgElements[i]; } } var scrollHeight = document.body.scrollTop; //滚动的高度 var bodyHeight = document.body.offsetHeight; //body(页面)可见区域的总高度 if (temp < scrollHeight) { //为true表示是向下滚动,否则是向上滚动,不需要执行动作。 for ( var k=0; k<lazyImgArr.length; k++) { var imgTop = lazyImgArr[k].offsetTop; //1305(图片纵坐标) if ((imgTop - scrollHeight) <= bodyHeight) { lazyImgArr[k].src = lazyImgArr[k].alt; lazyImgArr[k].className = "notlazy" } } temp = scrollHeight; } }; // --></script> </body> </html> |
js实现网页图片延时加载方法二:
再没贴代码之前先给大家讲下js实现图片延时加载的原理。
实现原理:
把所有需要延时加载的图片改成如下的格式:
1
|
<img lazy_src= "图片路径" border= "0" /> |
然后在页面加载时,把所有使用了lazy_src的图片都保存到数组里,然后在滚动时计算可视区域的top,然后把延时加载的图片中top小于当前可视区域(即图片出现在可视区域内)的图片的src的值用lazy_src的来替换(加载图片):
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
|
lazyLoad = ( function () { var map_element = {}; var element_obj = []; var download_count = 0; var last_offset = -1; var doc_body; var doc_element; var lazy_load_tag; function initVar(tags) { doc_body = document.body; doc_element = document.compatMode == \'BackCompat\' ? doc_body : document.documentElement; lazy_load_tag = tags || [ "img" , "iframe" ]; }; function initElementMap() { var all_element = []; //从所有相关元素中找出需要延时加载的元素 for ( var i = 0, len = lazy_load_tag.length; i < len; i++) { var el = document.getElementsByTagName(lazy_load_tag[i]); for ( var j = 0, len2 = el.length; j < len2; j++) { if ( typeof (el[j]) == "object" && el[j].getAttribute( "lazy_src" )) { element_obj.push(all_element[key]); } } } for ( var i = 0, len = element_obj.length; i < len; i++) { var o_img = element_obj[i]; var t_index = getAbsoluteTop(o_img); //得到图片相对document的距上距离 if (map_element[t_index]) { map_element[t_index].push(i); } else { //按距上距离保存一个队列 var t_array = []; t_array[0] = i; map_element[t_index] = t_array; download_count++; //需要延时加载的图片数量 } } }; function initDownloadListen() { if (!download_count) return ; var offset = (window.MessageEvent && !document.getBoxObjectFor) ? doc_body.scrollTop : doc_element.scrollTop; //可视化区域的offtset=document的高+ var visio_offset = offset + doc_element.clientHeight; if (last_offset == visio_offset) { setTimeout(initDownloadListen, 200); return ; } last_offset = visio_offset; var visio_height = doc_element.clientHeight; var img_show_height = visio_height + offset; for ( var key in map_element) { if (img_show_height > key) { var t_o = map_element[key]; var img_vl = t_o.length; for ( var l = 0; l < img_vl; l++) { element_obj[t_o[l]].src = element_obj[t_o[l]].getAttribute( "lazy_src" ); } delete map_element[key]; download_count--; } } setTimeout(initDownloadListen, 200); }; function getAbsoluteTop(element) { if (arguments.length != 1 || element == null ) { return null ; } var offsetTop = element.offsetTop; while (element = element.offsetParent) { offsetTop += element.offsetTop; } return offsetTop; } function init(tags) { initVar(tags); initElementMap(); initDownloadListen(); }; return { init: init } })(); |
使用方法:把页面上需要延时加载的图片src改成为lazy_src,然后把上面的js放到body最后面,然后调用:lazyLoad.init();
调戏的方法可以使用firebug来查看一时图片是否是延时加载。
另外:
如果你的页面上存在有内容切换的栏目的话,可能在切换时切换的内容里的图片可能会不显示,处理的方法是在内容时单独图片加载处理,如:
1
2
3
4
5
|
///切换内容的代码… chlid.find( "img[init_src]" ).each( function (){ $( this ).attr( "src" ,$( this ).attr( "init_src" )); $( this ).removeAttr( "init_src" ); }); |
原生态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
|
<!doctype html> <html> <head> <meta http-equiv= "Content-Type" content= "text/html; charset=utf-8" /> <title>通过原生js延迟加载图片</title> <style type= "text/css" > div{width:100px;height:100px;background: #F00;margin-bottom:30px} </style> </head> <body> " src= "a.gif" /></div> " src= "a.gif" /></div> " src= "a.gif" /></div> " src= "a.gif" /></div> </body> //以上图片测试时可用复制多点 <script type= "text/javascript" > ( function (){ //common function tagName(tagName){ return document.getElementsByTagName(tagName); } function $(id){ return document.getElementById(id); } function addEvent(obj,type,func){ if (obj.addEventListener){ obj.addEventListener(type,func, false ); } else if (obj.attachEvent){ obj.attachEvent( \'on\' +type,func); } } //这里可以按照需要配置些参数 var v={ eleGroup: null , eleTop: null , eleHeight: null , screenHeight: null , visibleHeight: null , scrollHeight: null , scrolloverHeight: null , limitHeight: null } //对数据进行初始化 function init(element){ v.eleGroup=tagName(element) screenHeight=document.documentElement.clientHeight; scrolloverHeight=document.body.scrollTop; for ( var i=0,j=v.eleGroup.length;i<j;i++){ if (v.eleGroup[i].offsetTop<=screenHeight && v.eleGroup[i].getAttribute( \'data-url\' )){ v.eleGroup[i].setAttribute( \'src\' ,v.eleGroup[i].getAttribute( \'data-url\' )); v.eleGroup[i].removeAttribute( \'data-url\' ) } } } function lazyLoad(){ if (document.body.scrollTop == 0){ limitHeight=document.documentElement.scrollTop+document.documentElement.clientHeight; } else { limitHeight=document.body.scrollTop+document.documentElement.clientHeight; } for ( var i=0,j=v.eleGroup.length;i<j;i++){ if (v.eleGroup[i].offsetTop<=limitHeight && v.eleGroup[i].getAttribute( \'data-url\' )){ v.eleGroup[i].src=v.eleGroup[i].getAttribute( \'data-url\' ); v.eleGroup[i].removeAttribute( \'data-url\' ) } } } init( \'img\' ) addEvent(window, \'scroll\' ,lazyLoad); })() </script> </html> |