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>

关注我

我的微信公众号:前端开发博客,在后台回复以下关键字可以获取资源。

  • 回复「小抄」,领取Vue、JavaScript 和 WebComponent 小抄 PDF
  • 回复「Vue脑图」获取 Vue 相关脑图
  • 回复「思维图」获取 JavaScript 相关思维图
  • 回复「简历」获取简历制作建议
  • 回复「简历模板」获取精选的简历模板
  • 回复「加群」进入500人前端精英群
  • 回复「电子书」下载我整理的大量前端资源,含面试、Vue实战项目、CSS和JavaScript电子书等。
  • 回复「知识点」下载高清JavaScript知识点图谱

每日分享有用的前端开发知识,加我微信:caibaojian89 交流