我想做的是:
$("img").bind('load', function() {
// do stuff
});
但是当图像从缓存中加载时,load事件不会触发。jQuery文档建议用一个插件来解决这个问题,但它不起作用
我想做的是:
$("img").bind('load', function() {
// do stuff
});
但是当图像从缓存中加载时,load事件不会触发。jQuery文档建议用一个插件来解决这个问题,但它不起作用
当前回答
你真的必须用jQuery来做吗?你也可以将onload事件直接附加到你的图像上;
<img src="/path/to/image.jpg" onload="doStuff(this);" />
它将在每次图像加载时触发,无论是否从缓存中加载。
其他回答
你也可以使用这段代码来支持加载错误:
$("img").on('load', function() {
// do stuff on success
})
.on('error', function() {
// do stuff on smth wrong (error 404, etc.)
})
.each(function() {
if(this.complete) {
$(this).load();
} else if(this.error) {
$(this).error();
}
});
我的简单解决方案,它不需要任何外部插件,对于常见情况应该足够了:
/**
* Trigger a callback when the selected images are loaded:
* @param {String} selector
* @param {Function} callback
*/
var onImgLoad = function(selector, callback){
$(selector).each(function(){
if (this.complete || /*for IE 10-*/ $(this).height() > 0) {
callback.apply(this);
}
else {
$(this).on('load', function(){
callback.apply(this);
});
}
});
};
像这样使用它:
onImgLoad('img', function(){
// do stuff
});
例如,要在你的图像加载淡出,你可以做:
$('img').hide();
onImgLoad('img', function(){
$(this).fadeIn(700);
});
或者作为替代,如果你喜欢jquery插件类的方法:
/**
* Trigger a callback when 'this' image is loaded:
* @param {Function} callback
*/
(function($){
$.fn.imgLoad = function(callback) {
return this.each(function() {
if (callback) {
if (this.complete || /*for IE 10-*/ $(this).height() > 0) {
callback.apply(this);
}
else {
$(this).on('load', function(){
callback.apply(this);
});
}
}
});
};
})(jQuery);
并这样使用它:
$('img').imgLoad(function(){
// do stuff
});
例如:
$('img').hide().imgLoad(function(){
$(this).fadeIn(700);
});
你可以使用JAIL插件来解决这个问题,它还允许你延迟加载图像(提高页面性能)并将回调作为参数传递
$('img').asynchImageLoader({callback : function(){...}});
HTML应该是这样的
<img name="/global/images/sample1.jpg" src="/global/images/blank.gif" width="width" height="height" />
对GUS示例的修改:
$(document).ready(function() {
var tmpImg = new Image() ;
tmpImg.onload = function() {
// Run onload code.
} ;
tmpImg.src = $('#img').attr('src');
})
在onload之前和之后设置源。
如果你想这样做,我可以给你一个小建议:
<div style="position:relative;width:100px;height:100px">
<img src="loading.jpg" style='position:absolute;width:100px;height:100px;z-index:0'/>
<img onLoad="$(this).fadeIn('normal').siblings('img').fadeOut('normal')" src="picture.jpg" style="display:none;position:absolute;width:100px;height:100px;z-index:1"/>
</div>
如果你在浏览器缓存图片时这样做,总是显示img没有问题,但在真实图片下加载img。