jQuery: new image added to DOM always has width 0 after loaded

travelboy picture travelboy · Dec 8, 2010 · Viewed 9.7k times · Source

I need to obtain the dimensions of an image, using a dynamically created image tag. It works. But ONLY using attr('width') and ONLY if I do NOT add the image to the DOM. Otherwise, dimensions returned are zero. Why? :)

this.img = $('<img/>', {'src': e.url} );           // generate image
this.img.appendTo('body');                         // add to DOM
this.img.load(function(self){return function(){    // when loaded call function
    console.log(self.img.attr('src'));
    console.log(self.img.attr('width'));
    console.log(self.img.width());
    console.log(self.img.css('width'));
}; }(this) );                                      // pass object via closure

So I generate the image, add it to the DOM and define a handler function to be called when the image is loaded. I'm using a closure to pass it a reference to the original object, called "self" within the closure. I'm dumping the image's URL to make sure the reference is alright. Output is:

pic.jpg
0
0
0px

Now here is the strange thing: if I remove the second line above (the appendTo), then it suddenly works, but only for attr('width'):

pic.jpg
1024
0
0px

This behavior doesn't make any sense to me. I would expect to get the actual image size in all six above cases. I know now how to work-around the problem, but I'd like to understand why it happens. Is it a bug? Or is there some logical reason for it?

The above results are for Safari. I just tested with Chrome and I got all correct values in the first example, but still two zeros in the second example. Very weird.

Answer

travelboy picture travelboy · Dec 11, 2010

I found a reliable solution for Safari:

  • Create the image
  • Attach the load() handler
  • Only AFTER that, set the src attribute!!

I still don't understand why width should ever return zero, but it seems that unexpected things happen if you attach the load handler only after setting the src. I got that idea only because I encountered yet another problem with IE (which didn't even call the load handler since it considered the image loaded before the handler was attached), so the lesson I've learnt is to always do things in the order described above.