1. 程式人生 > >三十五、懶載入(原生封裝)

三十五、懶載入(原生封裝)

var Lazy = {
        $:function(arg,context){
            var tagAll,n,eles=[],i,sub = arg.substring(1);
            context = context|| document;
            if(typeof arg =='string'){
                switch(arg.charAt(0)){
                    case '#':
                        return document.getElementById(sub);
                        break;
                    case '.':
                        if(context.getElementsByClassName) return context.getElementsByClassName(sub);
                        tagAll = Lazy.$('*');
                        n = tagAll.length;
                        for(i = 0;i<n;i++){
                            if(tagAll[i].className.indexOf(sub) > -1) eles.push(tagAll[i]);
                        }
                        return eles;
                        break;
                    default:
                        return context.getElementsByTagName(arg);
                        break;
                }
            }
        },
        getPos:function (node) {
            var scrollx = document.documentElement.scrollLeft || document.body.scrollLeft,
                    scrollt = document.documentElement.scrollTop || document.body.scrollTop;
            var pos = node.getBoundingClientRect();
            return {top:pos.top + scrollt, right:pos.right + scrollx, bottom:pos.bottom + scrollt, left:pos.left + scrollx }
        },
        bind:function(node,type,handler){
            node.addEventListener?node.addEventListener(type, handler, false):node.attachEvent('on'+ type, handler);
        },
        unbind:function(node,type,handler){
            node.removeEventListener?node.removeEventListener(type, handler, false):node.detachEvent('on'+ type, handler);
        },
        toArray:function(eles){
            var arr = [];
            for(var i=0,n=eles.length;i<n;i++){
                arr.push(eles[i]);
            }
            return arr;
        }
    };
    function imgLazyLoad(){
        var timer,screenHeight = document.documentElement.clientHeight;
        // 選擇所有圖片
        var allimg = Lazy.$('img');
        // 篩選CLASS為lazyload的圖片
        var elems = Lazy.$('.lazyload',allimg);
        // 轉換為真正的陣列
        elems = Lazy.toArray(elems);
        if(!elems.length) return;
        // 沒有發生滾動事件時如果圖片在可視範圍之內,也顯示
        for(var i = 0;i < elems.length;i++){
            // 獲取影象的父元素即包裹影象的元素,判斷影象是否在可視區域即直接判斷父元素是否可視
            var parent = elems[i].parentNode;
            var pos = Lazy.getPos(parent);
            var posT = pos.top;
            var posB = pos.bottom;
            // 沒有滾動條情況如果距離頂部的距離小於螢幕的高度則賦值SRC
            if(posT < screenHeight){
                elems[i].src = elems[i].getAttribute('data-img');
                // 移除後,陣列的長度減一,下一個下標需減一
                elems.splice(i--,1);
            }
        }
        // 繫結scroll事件
        Lazy.bind(window,'scroll',loading);
        Lazy.bind(window,'resize',loading);
        function loading(){
            timer && clearTimeout(timer);
            timer = setTimeout(function(){
                var scrollTop = document.documentElement.scrollTop || document.body.scrollTop;
                screenHeight = document.documentElement.clientHeight;
                for(var i = 0;i < elems.length;i++){
                    var parent = elems[i].parentNode;
                    var pos = Lazy.getPos(parent);
                    var posT = pos.top;
                    var posB = pos.bottom;
                    var screenTop = screenHeight+scrollTop;
                    // 元素頂部出現在可視區  或者  元素底部出現在可視區
                    if((posT > scrollTop && posT <  screenTop) || (posB > scrollTop && posB < screenTop)){
                        elems[i].src = elems[i].getAttribute('data-img');
                        elems.splice(i--,1);
                    }else{
                        // 去掉以下注釋開啟圖片預載入
//                         new Image().src = elems[i].getAttribute('data-img');
                    }
                }
                if(!elems.length){
                    Lazy.unbind(window,'scroll',loading);
                    Lazy.unbind(window,'resize',loading);
                }
            },10);
        }
    }
    imgLazyLoad();

  

data-img是圖片的真實路徑,src是佔位圖片盒子,避免錯亂,需加上class=“lazyload”,頁面使用的時候需要初始化方法imgLazyLoad();