I want to do:
$("img").bind('load', function() {
// do stuff
});
But the load event doesn't fire when the image is loaded from cache. The jQuery docs suggest a plugin to fix this, but it doesn't work
I want to do:
$("img").bind('load', function() {
// do stuff
});
But the load event doesn't fire when the image is loaded from cache. The jQuery docs suggest a plugin to fix this, but it doesn't work
Can I suggest that you reload it into a non-DOM image object? If it's cached, this will take no time at all, and the onload will still fire. If it isn't cached, it will fire the onload when the image is loaded, which should be the same time as the DOM version of the image finishes loading.
Javascript:
$(document).ready(function() {
var tmpImg = new Image() ;
tmpImg.src = $('#img').attr('src') ;
tmpImg.onload = function() {
// Run onload code.
} ;
}) ;
Updated (to handle multiple images and with correctly ordered onload attachment):
$(document).ready(function() {
var imageLoaded = function() {
// Run onload code.
}
$('#img').each(function() {
var tmpImg = new Image() ;
tmpImg.onload = imageLoaded ;
tmpImg.src = $(this).attr('src') ;
}) ;
}) ;
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.
If the src
is already set then the event is firing in the cache cased before you get the event handler bound. To fix this, you can loop through checking and triggering the event based off .complete
, like this:
$("img").one('load', function() {
// do stuff
}).each(function() {
if(this.complete) $(this).load();
});
Note the change from .bind()
to .one()
so the event handler doesn't run twice.
You may want to check out this plugin:
http://github.com/peol/jquery.imgloaded/raw/master/ahpi.imgload.js
A modification to GUS's example:
$(document).ready(function() {
var tmpImg = new Image() ;
tmpImg.onload = function() {
// Run onload code.
} ;
tmpImg.src = $('#img').attr('src');
})
Set the source before and after the onload.