I am having a bit of trouble working out when an image has been loaded.
I have been told that the following function will work but it isn\'t doing anything.
Use the ready
instead of load
event.
$("#images img:last").on('load',function(){
//do smth
});
The load
event of an image is fired when it's loaded (doh!), and critically, if you don't hook up your handler before it loads, your handler won't get called. Browsers will load resources in parallel, so you can't be sure (even in jQuery's ready
event saying the page's DOM is ready) that the image hasn't already been loaded when your code runs.
You can use the complete
property of the image object to know whether it's already been loaded, so:
var firstPhoto = $("#photos img:first");
if (firstPhoto[0].complete) {
// Already loaded, call the handler directly
handler();
}
else {
// Not loaded yet, register the handler
firstPhoto.load(handler);
}
function handler() {
alert("Image loaded!");
}
There may even be a race condition in that, if the browser in question really implements multi-threaded loading where the image load may occur on a different thread than the Javascript thread.
Of course, if your selector will match multiple images, you'll need to handle that; your selector looks like it's supposed to match only one, so...
Edit This version allows for multiple images, and I think it handles any non-Javascript race conditions (and of course, at present there are no Javascript race conditions; Javascript itself is single-threaded in browsers [unless you use the new web workers stuff]):
function onImageReady(selector, handler) {
var list;
// If given a string, use it as a selector; else use what we're given
list = typeof selector === 'string' ? $(selector) : selector;
// Hook up each image individually
list.each(function(index, element) {
if (element.complete) {
// Already loaded, fire the handler (asynchronously)
setTimeout(function() {
fireHandler.call(element);
}, 0); // Won't really be 0, but close
}
else {
// Hook up the handler
$(element).bind('load', fireHandler);
}
});
function fireHandler(event) {
// Unbind us if we were bound
$(this).unbind('load', fireHandler);
// Call the handler
handler.call(this);
}
}
// Usage:
onImageReady("#photos img:first");
A couple of notes:
event
object; you could modify it to do so if you liked, but of course, there'd be no event in the case where the image is already loaded, so it would be of limited utility.one
instead of bind
and unbind
, but I like the clarity and I'm paranoid. :-)try this:
$("#images img:last").one("load",function(){
//do something
}
or
$("#images img:last").one("ready",function(){
//do something
}