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 |
function
getElementsByClassName(str,root,tag){ if (root){ root = typeof
root == "string"
? document.getElementById(root) : root; } else
{ root = document.body; } tag = tag || "*" ; var
els = root.getElementsByTagName(tag),arr = []; for ( var
i=0,n=els.length;i<n;i++){ //k是一个数组 for ( var
j=0,k=els[i].className.split( " " ),l=k.length;j<l;j++){ if (k[j] == str){ arr.push(els[i]); break ; } } } return
arr; } //取元素的页面绝对 X位置 function
getLeft(El){ var
left = 0; do { left += El.offsetLeft; } while ((El = El.offsetParent).nodeName != ‘BODY‘ ); return
left; }; //取元素的页面绝对 Y位置 function
getTop(obj){ var
top = 0; while (obj){ top += obj.offsetTop; obj = obj.offsetParent; } return
top; }; function
lazyLoad(){ var
imgs =getElementsByClassName( "lazyLoad" , null , "img" ), top = document.body.scrollTop || document.documentElement.scrollTop, left = document.body.scrollLeft || document.documentElement.scrollLeft, screenHeight = window.screen.height, screenWidth = window.screen.width; for ( var
i=0,len=imgs.length; i < len; i++){ var
_top = getTop(imgs[i]); var
_left = getLeft(imgs[i]); //判断图片是否在显示区域内 if (_top <= screenHeight+top && _left <= screenWidth+left){ var
_src = imgs[i].getAttribute( ‘_src‘ ); //如果图片已经显示,则取消赋值 if (/imgs\/load.jpg$/.test(imgs[i].getAttribute( ‘src‘ ))){ imgs[i].src = _src; } } } } window.onload = window.onscroll = window.onresize= lazyLoad; |
1
2
3
4
5
6 |
<% for (int i = 0; i < 21; i++){ %> <img _src= "imgs/img<%=i%>.jpg"
class = "lazyLoad"
id= "<%=i%>"
data-i = <%=i%> src= "imgs/load.jpg"
style= "width:590px;height:500px;" > <% } |
关键点是1,把图片的src保存在自定义属性中,src统一用同一图片,浏览器会自动缓存。2,当图片出现在视口中则把src替换为真实的路径。这个时候会产生http请求,图片就加载了出来
纯js懒加载,java后台举例,布布扣,bubuko.com
原文:http://www.cnblogs.com/stay-poor/p/3721842.html