[转载]jquery实现图片延时加载

[转载]jquery实现图片延时加载 – Smile城 – 博客园.

原理:通过 JQuery 插件 lazyload 使得在浏览器可见区域外的图片不会被加载,当图片被用户滚动到浏览器可见区域时图片才进行加载,有点类似使用 Google 搜索图片时的效果。很明显,通过使用图片延时加载可以提高页面的加载速度。

 

实现过程:

首先是引入JQuery文件和插件文件。jQuery文件在这里我就不再赘述了。下面我贴出插件文件,我们将该文件命名为jQuery.lazyload.js

// JavaScript Document
/*
* Lazy Load - jQuery plugin for lazy loading images
*
* Copyright (c) 2007-2012 Mika Tuupola
*
* Licensed under the MIT license:
* http://www.opensource.org/licenses/mit-license.php
*
* Project home:
* http://www.appelsiini.net/projects/lazyload
*
* Version: 1.8.0
*
*/
(function($, window) {
var $window = $(window);

$.fn.lazyload = function(options) {
var elements = this;
var $container;
var settings = {
threshold : 0,
failure_limit : 0,
event : "scroll",
effect : "show",
container : window,
data_attribute : "original",
skip_invisible : true,
appear : null,
load : null
};

function update() {
var counter = 0;

elements.each(function() {
var $this = $(this);
if (settings.skip_invisible && !$this.is(":visible")) {
return;
}
if ($.abovethetop(this, settings) ||
$.leftofbegin(this, settings)) {
/* Nothing. */
} else if (!$.belowthefold(this, settings) &&
!$.rightoffold(this, settings)) {
$this.trigger("appear");
} else {
if (++counter > settings.failure_limit) {
return false;
}
}
});

}

if(options) {
/* Maintain BC for a couple of versions. */
if (undefined !== options.failurelimit) {
options.failure_limit = options.failurelimit;
delete options.failurelimit;
}
if (undefined !== options.effectspeed) {
options.effect_speed = options.effectspeed;
delete options.effectspeed;
}

$.extend(settings, options);
}

/* Cache container as jQuery as object. */
$container = (settings.container === undefined ||
settings.container === window) ? $window : $(settings.container);

/* Fire one scroll event per scroll. Not one scroll event per image. */
if (0 === settings.event.indexOf("scroll")) {
$container.bind(settings.event, function(event) {
return update();
});
}

this.each(function() {
var self = this;
var $self = $(self);

self.loaded = false;

/* When appear is triggered load original image. */
$self.one("appear", function() {
if (!this.loaded) {
if (settings.appear) {
var elements_left = elements.length;
settings.appear.call(self, elements_left, settings);
}
$("<img alt="" />")
.bind("load", function() {
$self
.hide()
.attr("src", $self.data(settings.data_attribute))
[settings.effect](settings.effect_speed);
self.loaded = true;

/* Remove image from array so it is not looped next time. */
var temp = $.grep(elements, function(element) {
return !element.loaded;
});
elements = $(temp);

if (settings.load) {
var elements_left = elements.length;
settings.load.call(self, elements_left, settings);
}
})
.attr("src", $self.data(settings.data_attribute));
}
});

/* When wanted event is triggered load original image */
/* by triggering appear. */
if (0 !== settings.event.indexOf("scroll")) {
$self.bind(settings.event, function(event) {
if (!self.loaded) {
$self.trigger("appear");
}
});
}
});

/* Check if something appears when window is resized. */
$window.bind("resize", function(event) {
update();
});

/* Force initial check if images should appear. */
update();

return this;
};

/* Convenience methods in jQuery namespace. */
/* Use as $.belowthefold(element, {threshold : 100, container : window}) */

$.belowthefold = function(element, settings) {
var fold;

if (settings.container === undefined || settings.container === window) {
fold = $window.height() + $window.scrollTop();
} else {
fold = $(settings.container).offset().top + $(settings.container).height();
}

return fold};

$.rightoffold = function(element, settings) {
var fold;

if (settings.container === undefined || settings.container === window) {
fold = $window.width() + $window.scrollLeft();
} else {
fold = $(settings.container).offset().left + $(settings.container).width();
}

return fold = $(element).offset().top + settings.threshold + $(element).height();
};

$.leftofbegin = function(element, settings) {
var fold;

if (settings.container === undefined || settings.container === window) {
fold = $window.scrollLeft();
} else {
fold = $(settings.container).offset().left;
}

return fold &gt;= $(element).offset().left + settings.threshold + $(element).width();
};

$.inviewport = function(element, settings) {
return !$.rightofscreen(element, settings) &amp;&amp; !$.leftofscreen(element, settings) &amp;&amp;
!$.belowthefold(element, settings) &amp;&amp; !$.abovethetop(element, settings);
};

/* Custom selectors for your convenience. */
/* Use as $("img:below-the-fold").something() */

$.extend($.expr[':'], {
"below-the-fold" : function(a) { return $.belowthefold(a, {threshold : 0}); },
"above-the-top" : function(a) { return !$.belowthefold(a, {threshold : 0}); },
"right-of-screen": function(a) { return $.rightoffold(a, {threshold : 0}); },
"left-of-screen" : function(a) { return !$.rightoffold(a, {threshold : 0}); },
"in-viewport" : function(a) { return !$.inviewport(a, {threshold : 0}); },
/* Maintain BC for couple of versions. */
"above-the-fold" : function(a) { return !$.belowthefold(a, {threshold : 0}); },
"right-of-fold" : function(a) { return $.rightoffold(a, {threshold : 0}); },
"left-of-fold" : function(a) { return !$.rightoffold(a, {threshold : 0}); }
});

})(jQuery, window);

下面我们来看引入方式。

       你必须改变你的HTML代码。将SRC属性的占位符图像。演示页面使用1×1像素的灰度GIF 的真实图像的URL必须投入原始数据的属性。

  

  下面我们来看在html代码中需要书写些什么,这是调用方式

<script type="text/javascript">// <![CDATA[
$(document).ready(function() {            $("img").lazyload({                   effect: "fadeIn"            });        });
// ]]></script>

到这里,其实已经实现了我们想要的效果了,图片将会以 fadeIn 形式被载入。

但是,我们在这里还是不得不提一下,这个插件的其他的功能。

1.可以设置阀值来控制 灵敏度,下边代码把阀值设置成200 表明当图片没有看到之前先load 200像素。


 

1 $("img").lazyload({ threshold : 200 });

 

2.可以通过设置占位符图片和自定事件来触发加载图片事件


 

1 $("img").lazyload({ 2       placeholder: "img/grey.gif",      event: "click" 
3  });

 

3.事件触发加载,事件可以是任何 jQuery 时间, 如: click 和 mouSEOver. 你还可以使用自定义的事件, 如: sporty 和 foobar. 默认情况下处于等待状态, 直到用户滚动到窗口上图片所在位置. 在灰色占位图片被点击之前阻止加载图片, 你可以这样做:

1 $("img").lazyload({ 2       placeholder: "img/grey.gif",      event: "click" 
3  });

 

延迟加载图片,Lazy Load 插件的一个不完整的功能, 但是这也能用来实现图片的延迟加载. 下面的代码实现了页面加载完成后再加载. 页面加载完成 5 秒后, 指定区域内的图片会自动进行加载.

$(function() {
$("img:below-the-fold").lazyload({
placeholder: "img/grey.gif",
event: "sporty"
});
});
$(window).bind("load", function() {
var timeout = setTimeout(function() {
$("img").trigger("sporty") }, 5000);
});

更多的方法和资料,请参见官网http://www.appelsiini.net/projects/lazyload

这里需要特别说明一下,jquery的版本不要太低哦,1.3的就不会出效果的。

这是我写的一个小demo,拿去参考一下还是极好的。

下载地址:http://files.cnblogs.com/wscdzl/demo.rar

  

赞(0) 打赏
分享到: 更多 (0)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

微信扫一扫打赏