[jQuery] bind('load') on an <img> element doesn't return the image properly

[jQuery] bind('load') on an <img> element doesn't return the image properly


I'm not sure if this is actually the problem or not, but it's the
result. I am trying to build on Luke Lutman's preloading images
snippet (http://www.mail-archive.com/discuss@jquery.com/
msg14399.html). Here's what I'm doing ( -- it's wrapped in $
(window).bind('load') -- ) :
var toPreload = new Array();
// toPreload gets dynamically populated with a bunch of string values
for image sources.
// essentially no different than this:
toPreload = ["image1-on.gif", "image2-on.gif", "image3-on.gif"]
$('<img>').bind('load', function(e) {
if(toPreload[1]) {
this.src = toPreload.shift();
console.log("loaded: "+e.target.nodeType);
}
}).trigger('load');
Now what that SHOULD (and does) do is preload all of the images. Once
each load event completes, it will fire the 'trigger' call and load
the next img src until the toPreload array is empty. Very nifty little
cycle (thank you Luke..). Here's where the problem is:
The output in firebug from the console.log() statement looks like
this:
-----------------------
loaded: 1
loaded: 9
loaded: 9
-----------------------
So that means that the first time 'load' is called, the
eventObject.target is properly pointing to the <img> element that I've
created to load into. BUT, every time after that, the
eventObject.target is pointing to the document.
WHY??
The reason this matters to me (the images still load properly) is that
I am trying to build in error detection so that if one of the images
in the toPreload array doesn't actually exist and can't be loaded,
that image will be skipped, and the cycle will continue to load the
rest of the images. As it stands, Luke's snippet breaks if any of the
images cannot be found.
I've chained a call to .error() after the .trigger() - which fires as
soon as one of the images can't load. I haven't fully decided how I
want to go about handling this, but having the proper reference to
event.target inside the load handler would be a good start I think.
Any thoughts?
Thanks a lot!
Carter