jQuery的图片懒加载

时间:2021-11-13 19:29:33

jQuery的图片懒加载

function imgLazyLoad(options) {
var settings = {
Id: $('img'),
threshold: 100,
effectspeed: 0,
effect: "fadeIn"
};
$.extend(settings, options);
var $this = settings.Id; var timeout = null;
$(window).bind('load resize', loadImg)
$(window).scroll(function () {
if (timeout) { clearTimeout(timeout); }
timeout = setTimeout(loadImg ? loadImg : "", 100);
}); function loadImg() {
settings.Id.each(function () {
if (!belowthefold(this)) {
if ($(this).is(':visible')) {
$(this).trigger("appear");
}
}
});
}
return $this.each(function (i) {
var self = this;
//$(self).data('t', $(self).offset().top)
if (belowthefold(self)) {
self.loaded = false;
} else {
if ($(self).is(':visible')) {
$(self).attr("src", $(self).attr("original"));
self.loaded = true;
}
}
$(self).one("appear",
function () {
if (!this.loaded) {
$("<img />").bind("load",
function () {
$(self).hide().attr("src", $(self).attr("original"))[settings.effect](settings.effectspeed);
self.loaded = true
}).attr("src", $(self).attr("original"))
}
});
});
function belowthefold(element) {
var fold = $(window).height() + $(window).scrollTop()
return fold <= $(element).offset().top - settings.threshold;
};
}
imgLazyLoad({threshold:0,effectspeed:800})