Jquery occasionally returns zero height and width on image

You're right, the image is not loaded.

Worst, in IE, sometimes the size reported is something like 40x60 (the small icon you see when the image is not loaded yet).

jQuery reports that the load event can be used with images: http://api.jquery.com/load-event/

I tried a long time ago to solve this problem, cross browser, and I ended up polling the image sizes to trigger a custom "load" event.

Thanks


You can bind a load event handler to the element before adding it to the DOM, to get the width/height once it's available. You can also explicitely set the width/height of the image using CSS or inline attributes.

//create an img element, passing attribute values as we do, then bind an event handler to the `load` event for the image
var $img = $('<img />', { src : '/photos/' + file, id : 'lightImage' }).on('load', function () {

    //now that the image has loaded we can be sure the height/width values we receive are accurate
    var imageHeight = $(this).height(),
        imageWidth  = $(this).width();

    console.log(imageHeight + 'x' + imageWidth);
});

//now change the HTML of the container, emptying the container, then appending a div element with the `dialogue` class which also has a child img element (our image from above)
$('#dialogueContainer').html($('<div />', { class : 'dialogue' }).html($img));

I like to bind the load event handler to the element before adding it to the DOM or changing it's source, this way you know the load event is in place when the image actually loads (which can happen quickly from cache).

Note that .on() is new in jQuery 1.7 and in this case replaces .bind() (of earlier versions).

Update

I would like to stress the fact that if you know the dimensions of your image you should explicitly declare them (this is best practice for faster browser rendering):

<img width="100px" height="200px" src="..." />