I’m appending an image in my JavaScript code but want to get its correct width and height. Is this possible? My code looks like this:
$('body').append('<img src="path.jpg" width="'
+ w + '" height="' + h + '" alt="" />');
I know how to get the image width after it has been loaded but I’m loading an img and want to get its corresponding width and height directly. Any tips?
The HTML spec recommends to specify
heightandwidthfor<img>as a hint for a visual agent, which mixes the markup and the style rules to build a visual representation of a HTML document. In the CSS box model, the image dimensions are intrinsic, ie they are implicit in the binary blob. This means that a browser has to wait a HTTP response before deciding how big the image is and thus how to lay out and position siblings and parents. Specifying the dimensions in the HTML pages helps the browser to quickly render the page, because it can assign width and height before downloading the image from the server.At this point it should be clear that there can be no way to access the image width on the client before downloading it. When the Javascript knows it, the browser already knew, and you state it’s too late for your requirements.
So the only option to hint the browser is measuring the image on the server side. It can be done on a per-request basis (but it’s a waste of resources), or it can be done once when the image is first uploaded (and then retrieved from a database), or eventually it can be assumed constant, for example if it’s a profile picture that your service will always grow or shrink to be exactly
W x Hpixels big (this could be a configuration parameter).