jQuery图片懒加载代码

jquery图片懒加载代码:来自@前端老徐

<script>
/*
   @作者:外号老徐
   @日期:2015.04.25
   @邮箱:442413729@qq.com
   @网址:http://www.loveqiao.com
*/
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})
</script>
原文链接:jQuery图片懒加载代码 版权所有,转载时请注明出处,违者必究。
注明出处格式:前端开发博客 (http://caibaojian.com/js-lazyload.html)

发表评论

请登录后发表评论: