The HTML spec recommends to specify height
and width
for <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 H
pixels big (this could be a configuration parameter).