图片延迟加载

fwxstar 2018-05-30 761次浏览

摘要: 图片延迟加载Html<ul id="oUl">     <li><img _src="ima...

图片延迟加载

  1. Html

<ul id="oUl">
    <li><img _src="images/1.jpg"  src="images/pce.jpg"  alt=""/></li>
    <li><img _src="images/2.jpg"  src="images/pce.jpg"  alt=""/></li>
    <li><img _src="images/3.jpg"  src="images/pce.jpg"  alt=""/></li>
    <li><img _src="images/4.jpg"  src="images/pce.jpg"  alt=""/></li>
    <li><img _src="images/5.jpg"  src="images/pce.jpg"  alt=""/></li>
    <li><img _src="images/6.jpg"  src="images/pce.jpg"  alt=""/></li>
    <li><img _src="images/7.jpg"  src="images/pce.jpg"  alt=""/></li>
    <li><img _src="images/8.jpg"  src="images/pce.jpg"  alt=""/></li>
    <li><img _src="images/9.jpg"  src="images/pce.jpg"  alt=""/></li>
    <li><img _src="images/10.jpg" src="images/pce.jpg"   alt=""/></li>
    <li><img _src="images/11.jpg" src="images/pce.jpg"   alt=""/></li>
    <li><img _src="images/12.jpg" src="images/pce.jpg"   alt=""/></li>
    <li><img _src="images/1.jpg"  src="images/pce.jpg"  alt=""/></li>
    <li><img _src="images/2.jpg"  src="images/pce.jpg"  alt=""/></li>
    <li><img _src="images/3.jpg"  src="images/pce.jpg"  alt=""/></li>
    <li><img _src="images/4.jpg"  src="images/pce.jpg"  alt=""/></li>
    <li><img _src="images/5.jpg"  src="images/pce.jpg"  alt=""/></li>
    <li><img _src="images/6.jpg"  src="images/pce.jpg"  alt=""/></li>
    <li><img _src="images/7.jpg"  src="images/pce.jpg"  alt=""/></li>
    <li><img _src="images/8.jpg"  src="images/pce.jpg"  alt=""/></li>
    <li><img _src="images/9.jpg"  src="images/pce.jpg"  alt=""/></li>
    <li><img _src="images/10.jpg" src="images/pce.jpg"   alt=""/></li>
    <li><img _src="images/11.jpg" src="images/pce.jpg"   alt=""/></li>
    <li><img _src="images/12.jpg" src="images/pce.jpg"   alt=""/></li>
</ul>

Js

window.onload= function () {
            var oUl=document.getElementById("oUl");
            var oImg=oUl.getElementsByTagName("img");

            showImg();
            window.onscroll=showImg;

            function showImg(){
                var scrollTop=document.documentElement.scrollTop||document.body.scrollTop;
                for(var i=0;i<oImg.length;i++){
                    if(!oImg[i].load && getTop(oImg[i])<scrollTop+document.documentElement.clientHeight){
                        oImg[i].src=oImg[i].getAttribute("_src");
                        oImg[i].load=true;
                    }
                }
            }

            function getTop(obj) {
                var iTop = 0;
                while(obj) {
                    iTop += obj.offsetTop;
                    obj = obj.offsetParent;
                }
                return iTop;
            }
        }