图片预加载功能

 

首先看看一篇文章写的延迟加载的一个例子

http://www.cnblogs.com/ranzige/p/js_pic_preload.html   

 

 

下面我经常使用一个延迟加载例子:

/**
* 延迟加载图片
* @param $image
* @param src
* @param callback
*/
var loadImage = function ($image, src, callback) {
if ($.browser.webkit) {
$image.attr('src', '');
}
$image.attr('src', src );

$image.bind("load", function (evt) {
if ($image.width() === 0) {
return;
}
$image.unbind("load");
callback($image);

}).each(function () {
if ($image[0].complete) {
$image.trigger("load");
}
});
};

 

<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Carousel</title>
<style type="text/css">
img { border:none;}
</style>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js"></script>
<script type="text/javascript">

$(function(){

var loadImage = function ($image, src, callback) {
if ($.browser.webkit) {
$image.attr('src', '');
}
$image.attr('src', src );

// Bind the load event BEFORE setting the src.
$image.bind("load", function (evt) {
// If no valid width, image hasn't actually loaded.
if ($image.width() === 0) {
return;
}
// Image has loaded, so unbind event and call callback.
$image.unbind("load");
callback($image);

}).each(function () {
// For Gecko based browsers, check the complete property,
// and trigger the event manually if image loaded.
if ($image[0].complete) {
$image.trigger("load");
}
});
// For Webkit browsers, the following line ensures load event fires if
// image src is the same as last image src. This is done by setting
// the src to an empty string initially.
};

loadImage($('#pic2'),'pic2.png',function($image){
orgWidth = $image.width();
orgHeight = $image.height();
})
})
</script>

</head>
<body>

<div class="carousel" ><!-- This is the wrapping element -->
<a href="http://en.wikipedia.org/wiki/Self-portrait_(Leonardo_da_Vinci)" target="_blank">
<img src="pic1.png" alt="Pic 1"/>
</a>
<img id="pic2" src="" alt="Pic 2"/>
<img id="pic3" src="pic3.png" alt="Pic 3"/>
<img src="pic4.png" alt="Pic 4"/>
<img src="pic5.png" alt="Pic 5"/>
<img src="pic6.png" alt="Pic 6"/>
<img src="pic7.png" alt="Pic 7"/>
<img src="pic8.png" alt="Pic 8"/>
<img src="pic9.png" alt="Pic 9"/>
</div>

年是科技大会
</body>
</html>

posted @ 2014-02-11 10:34  xiezhenzhong  阅读(171)  评论(0编辑  收藏  举报