Picture delay loading can save us bandwidth, to obtain a better user experience, especially for many pictures of the site, this point is crucial, today zero to discuss with you about the picture delay loading principle and implementation code.
Picture Delay Loading principle
Picture delay loading principle is in the HTML picture src fills in is not the real picture address, but takes a custom attribute to assign the picture address to the IMG label, for example: src= "Img/loading.gif" data-url= "Img/1.jpg", And then through JS to determine the browser scroll event, to reach a place when the custom attributes inside the picture real address to the current IMG tag src, so as to achieve the picture dynamic display. In real projects, the addresses of these images can be passed through Ajax and assigned to the IMG custom properties.
Native JS implementation picture Delay Loading instance:
Text content looks a bit boring after all, I wrote a simple demo, now put all the code posted out, the need for friends can directly copy the past, look at the code to understand.
| The code is as follows |
Copy Code |
| <! DOCTYPE html> <meta http-equiv= "Content-type" content= "text/html; Charset=utf-8 "> <title> Picture Delay Loading </title> <style> Img{display:block;width:350px;height:245px;background:url (img/loading.gif) Center Center No-repeat} </style> <body> <div id= "div" > <br> <br> <br> <br> <br> <br> <br> <br> <br> <br> <br> <br> <br> <br> <br> <br> <br> <br> <br> <br> <br> <br> <br> <br> </div> <script type= "Text/javascript" > var Obj=document.getelementbyid ("Div"). getElementsByTagName ("img"), H=window.innerheight | | Document.documentElement.clientHeight; for (Var i=0;i<obj.length;i++) { Obj[i].url=obj[i].getattribute ("Data-url"); Obj[i].top=obj[i].offsettop; Obj[i].flag=true; Prevent the browser from loading pictures, so that when the picture is loaded successfully, scrolling browser will not load the picture again; } var fnload = function (obj) { var t = Document.body.scrollTop | | Document.documentElement.scrollTop; if (t+h>obj.top+200&&obj.top>t) {//give a 200 in order to improve the user to see the picture loading state, more friendly settimeout (function () { Obj.src=obj.url; Obj.flag=false; },500) } } Window.onscroll = Window.onload=function () { for (Var i=0;i<obj.length;i++) { if (Obj[i].flag) { Fnload (Obj[i]); } } } </script> </body> |