所谓懒加载,就是为了减轻服务器的压力,每次请求的数据不会很多,当达到触发条件的时候,再次去请求数据,接下来我们就用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 | <!DOCTYPE HTML> <html> <head> <title></title> <meta charset="utf-8"> <meta name="Author" content=""> <style type='text/css'> *{ margin:0; padding:0;} img{ display:block; margin-bottom:20px; } </style> </head> <body> <img src="img/1.jpg" alt="" width="500" height="auto" /> <img src="img/2.jpg" alt="" width="500" height="auto" /> <img src="img/3.jpg" alt="" width="500" height="auto" /> <img src="img/4.jpg" alt="" width="500" height="auto" /> <img src="img/5.jpg" alt="" width="500" height="auto" /> <img src="img/6.jpg" alt="" width="500" height="auto" /> <img src="img/7.jpg" alt="" width="500" height="auto" /> <img src="img/8.jpg" alt="" width="500" height="auto" /> <img src="img/9.jpg" alt="" width="500" height="auto" /> <img src="img/10.jpg" alt="" width="500" height="auto" /> <img src="img/11.jpg" alt="" width="500" height="auto" /> <img src="img/12.jpg" alt="" width="500" height="auto" /> <img src="img/13.jpg" alt="" width="500" height="auto" /> <img src="img/14.jpg" alt="" width="500" height="auto" /> <script type="text/javascript"> var oImg = document.getElementsByTagName('img'); var length = oImg.length; for ( var i=0;i<length;i++ ) { oImg[i].dataSrc = oImg[i].src; oImg[i].src = 'img/loading.jpg'; } window.onload = function(){ var arr = []; for ( var i=0;i<length;i++ ) { arr[i] = oImg[i]; } imgShow(); window.onscroll = imgShow; function imgShow(){ for ( var i=arr.length-1;i>=0;i-- ) { var top = offsetTop( arr[i] ); var scrollTop = document.documentElement.scrollTop || document.body.scrollTop; if ( top < ( scrollTop + winSize().height ) ) { arr[i].src = arr[i].dataSrc; arr.slice( i,1 ); } } }; function offsetTop(obj){ var top = 0; while ( obj != document.body ) { top += obj.offsetTop; obj = obj.parentNode; }; return top; }; function winSize() { var e = window,a = 'inner'; if (!('innerWidth' in window )){ a = 'client'; e = document.documentElement || document.body; }; return { width : e[ a+'Width' ] , height : e[ a+'Height' ] }; }; }; </script> </body> </html> //1-14.jpg是加载的图片,loading.jpg是显示正在加载的图片 |
7