因为之前的代码是基于 jQuery mobile,只用到了其中的一个事件:监听滚动条停止滚动,因为这个单独引用 jQuery mobile 成本有点儿高,所以就整了个事件来替换 jQuery mobile,并对代码进行了重构;
小二,上代码~
监听滚动条停止滚动代码:https://github.com/ssorallen/jquery-scrollstop
var lazyLoad = {
belowTheFold: function(element) {
var _fold = $(window).height() + $(window).scrollTop();
return _fold <= $(element).offset().top;
},
aboveTheTop: function(element) {
var _top = $(window).scrollTop();
return _top >= $(element).offset().top + $(element).height();
},
inViewport: function(element) {
return !this.belowTheFold(element) && !this.aboveTheTop(element);
},
loadImg: function(ele) {
if (ele.find("img[_src]").length) {
var img = ele.find("img[_src]"),
imgUrl = img.attr("_src");
img.attr("src", imgUrl).load(function() {
img.removeAttr("_src");
})
};
},
init: function(list) {
var that = this,
refreshTimer = null;
$(window).on("scrollstop", function() {
refreshTimer && (clearTimeout(refreshTimer), refreshTimer = null);
refreshTimer = setTimeout(function() {
return list.each(function(i){
var ele = list.eq(i);
that.inViewport(ele) && that.loadImg(ele);
});
}, 1e3)
})
}
};
// 调用方法
lazyLoad.init($("#bookList li"));