js实现图片(高度不确定)懒加载

最近一直在弄广告页,由于广告页几乎都是图片拼凑起来的,为了减少服务器压力和带宽,采用图片懒加载方式,但是我们的图片高度又不确定,所以我在网上下载了echo.js自己改了一下。

大体思路是:让首页先加载几张图片(根据切片大小自己确定能够铺满首页),之后滚动鼠标时在判断下一张图片是否出现,然后将data-echo的值给src,下面是我代码,有不当之处还望大家多多指点!

window.Echo = (function(window, document, undefined) {
    'use strict';
    var store = [],
    offset,//距离多远时开始加载
    throttle,//加载图片时间
    firstnum,//首页显示图片数量
    poll;
    var _inView = function(el,num) {
        var inView;
        if(num<=firstnum){
            inView=true;
        }else{
            var coords = el.getBoundingClientRect();
            inView=(coords.top >= 0 && coords.left >= 0 && coords.top) <= (window.innerHeight || document.documentElement.clientHeight) + parseInt(offset);
        }
        return inView;
    };
    
    var _pollImages = function() {
        var num=0;
        for(var i=0;i<store.length;i++){
            var self=store[i];
            num++;
            if(_inView(self,num)){
                self.src = self.getAttribute('data-echo');
            }
        }
    };
    var _throttle = function() {
        clearTimeout(poll);
        poll = setTimeout(_pollImages, throttle);
    };
    var init = function(obj) {
        var nodes = document.querySelectorAll('[data-echo]');
        var opts = obj || {};
        offset = opts.offset || 0;
        throttle = opts.throttle || 250;
        firstnum=opts.firstnum || 0;
        for (var i = 0; i < nodes.length; i++) {
            store.push(nodes[i]);
        }
        _throttle();
        if (document.addEventListener) {
            window.addEventListener('scroll', _throttle, false);
        } else {
            window.attachEvent('onscroll', _throttle);
        }
    };
    return {
        init: init,
        render: _throttle
    };
})(window, document);

 调用方法:

Echo.init({
	offset:10,
	throttle:0,
	firstnum:3
})

  大家看了我的随笔记得发表一下意见,共同进步!

生活中不可能到处顺利,包括工作!
原文地址:https://www.cnblogs.com/tizi/p/8674654.html