The browser does NOT provide a special event that will tell you the earliest possible time that it knows the size for an image (before it has finished downloading the image). All you can do is set up an appropriate load handler to know when the image has finished downloading and then its size is known.
A brute force way that seems to work in some browsers for getting the height and width a little before the full image has loaded is to poll the loading image for the existence of .width
and .height
. In this jsFiddle in Chrome, it is sometimes available before the onload()
event fires. I've not tested this in other browsers.
If you go the route of an onload handler and your image tag with the .src
specific is in the HTML of the page, the ONLY way to make sure you get notified when it is loaded is to put an inline image handler so the handler is installed from the very beginning:
<img src="xxx.jpg" onload="handleLoad(this)">
Trying to attach an event handler from your page javascript may be too late (after the image has finished loading). The browser does not provide intermediate event info (like when it knows the size, but hasn't finished downloading the image).
For dynamically created image objects (image objects you create in your javascript), you can attach a listener for the load event when you create the object.
var img = new Image();
img.onload = function() {
// the image is now loaded here and height and width are known
};
img.src = "xxxx.jpg";
Note: when doing this with dynamically created image objects, you MUST set the onload
handler BEFORE you set the .src
value. In some versions of IE, if the image is cached, the load event will fire immediately when the .src
value is set so if you set .src
first and then set the onload
handler, you will miss the onload
event if the image is in the browser cache.