I want to do:
$(\"img\").bind(\'load\', function() {
// do stuff
});
But the load event doesn\'t fire when the image is loaded from cache
You can also use this code with support for loading error:
$("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();
}
});
Do you really have to do it with jQuery? You can attach the onload
event directly to your image as well;
<img src="/path/to/image.jpg" onload="doStuff(this);" />
It will fire every time the image has loaded, from cache or not.
By using jQuery to generate a new image with the image's src, and assigning the load method directly to that, the load method is successfully called when jQuery finishes generating the new image. This is working for me in IE 8, 9 and 10
$('<img />', {
"src": $("#img").attr("src")
}).load(function(){
// Do something
});
I just had this problem myself, searched everywhere for a solution that didn't involve killing my cache or downloading a plugin.
I didn't see this thread immediately so I found something else instead which is an interesting fix and (I think) worthy of posting here:
$('.image').load(function(){
// stuff
}).attr('src', 'new_src');
I actually got this idea from the comments here: http://www.witheringtree.com/2009/05/image-load-event-binding-with-ie-using-jquery/
I have no idea why it works but I have tested this on IE7 and where it broke before it now works.
Hope it helps,
The accepted answer actually explains why:
If the src is already set then the event is firing in the cache cased before you get the event handler bound.
I can give you a little tip if you want do like this:
<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>
If you do that when the browser caches pictures, it's no problem always img shown but loading img under real picture.
You can solve your problem using JAIL plugin that also allows you to lazy load images (improving the page performance) and passing the callback as parameter
$('img').asynchImageLoader({callback : function(){...}});
The HTML should look like
<img name="/global/images/sample1.jpg" src="/global/images/blank.gif" width="width" height="height" />