Reputation: 840
I'm wondering if it's possible to get sizes (width and height) of an image before it's loaded? Unfortunately I can't use something like this code:
$('img').load(function() {
alert(this.width + ' ' + this.height);
});
I can't wait while image is loading, I need to know sizes of an image at the beggining.
Is it possible or should I use for example PHP and getimagesize() function and pass it to HTML?
Upvotes: 3
Views: 5472
Reputation: 53136
I cannot think of any genuine reason why you can't load your image and then before it is placed in the document to figure out the height. You can wait until the image has loaded. If you can't then you have totally designed your application wrong. (In a non judgmental sort of way :) )
Upvotes: 0
Reputation: 1074148
You can't. The browser doesn't report the dimensions of the image until it's loaded. You'll have to get the information server-side, or change your approach so you don't need to know before it loads.
If you just need to know the size of the image before you put it in the page (rather than literally before you load it), you can do this:
img = new Image();
img.onload = function() {
// Here, you can reliably use `width` and `height`
display("Loaded, size is " + this.width + "x" + this.height);
};
img.src = "the/path/to/the/image/goes/here";
It's important to hook the load
event before setting the src
, in case the image is in cache and the event fires immediately.
(I don't advocate using DOM0 style handlers like onload
, but they're useful in quick examples.)
Upvotes: 9