48

I've read about various kinds of ways getting image dimensions once an image has fully loaded, but would it be possible to get the dimensions of any image once it just started to load?

I haven't found much about this by searching (which makes me believe it's not possible), but the fact that a browser (in my case Firefox) shows the dimensions of any image I open up in a new tab right in the title after it just started loading the image gives me hope that there actually is a way and I just missed the right keywords to find it.

user828591
  • 1,212
  • 2
  • 17
  • 32

4 Answers4

64

You are right that one can get image dimensions before it's fully loaded.

Here's a solution (demo):

var img = document.createElement('img');

img.src = 'some-image.jpg';

var poll = setInterval(function () {
    if (img.naturalWidth) {
        clearInterval(poll);
        console.log(img.naturalWidth, img.naturalHeight);
    }
}, 10);

img.onload = function () { console.log('Fully loaded'); }
katspaugh
  • 17,449
  • 11
  • 66
  • 103
  • 5
    This is very cool to know. The one thing I'd add is if the img has a height or width set either on the image tag or in the CSS, then your method just returns that value, not the natural size of the image. Some browsers support the naturalWidth and naturalSize attributes. You can see that here in this mod of your fiddle http://jsfiddle.net/jfriend00/rQwD4/ – jfriend00 Jul 04 '11 at 20:59
  • @katspaugh Thanks for your comment and the provided demo, it's what I've been looking for! @jfriend00 I knew about the natural size problem, but thanks for the modified example, means less work for me. – user828591 Jul 05 '11 at 18:27
  • 2
    Seems to be more efficient if you invoke `clearInterval` as soon as you get a non-zero value for both `naturalWidth` and `naturalHeight`, like how aleemb's solution does it (as opposed to waiting until image is loaded). – doubleDown Jan 05 '17 at 07:51
  • You can put the same logic inside the `onload` function instead of the poll. Also manage errors with onError – Jeffrey Nicholson Carré Jul 03 '22 at 07:39
  • interesting, any idea about how much faster can you get the information in average (after which percentage of the loading process) – Vincent Dec 08 '22 at 03:43
11

The following code returns width/height as soon as it's available. For testing change abc123 in image source to any random string to prevent caching.

There is a JSFiddle Demo as well.

<div id="info"></div>
<img id="image" src="https://upload.wikimedia.org/wikipedia/commons/d/da/Island_Archway,_Great_Ocean_Rd,_Victoria,_Australia_-_Nov_08.jpg?abc123">

<script>
getImageSize($('#image'), function(width, height) {
    $('#info').text(width + ',' + height);
});

function getImageSize(img, callback) {
    var $img = $(img);

    var wait = setInterval(function() {
        var w = $img[0].naturalWidth,
            h = $img[0].naturalHeight;
        if (w && h) {
            clearInterval(wait);
            callback.apply(this, [w, h]);
        }
    }, 30);
}
</script>
aleemb
  • 31,265
  • 19
  • 98
  • 114
  • 9
    This is a nice jQuery alternative, but should not be the accepted answer as it adds dependency that has not been required by the OP. – rzb Sep 29 '17 at 08:48
  • Not only that, but it is completely unnecessary. He wraps img in a jQuery, and then takes the first element of that same jQuery. – Gregory Magarshak Jun 14 '23 at 11:03
2

You can achieve this with ResizeObserver

new ResizeObserver((e, observer) => {
  img.remove();
  observer.disconnect();
  console.log(`${img.naturalWidth},${img.naturalHeight}`);
}).observe(img);
document.body.appendChild(img);

See https://codepen.io/noamr/pen/NWOaqjp?editors=1111

  • Perfect solution to me. I'd never realised `ResizeObserver` can do this. Much better than the `setInterval` answers! – Benber Zhang Jun 16 '23 at 06:07
1

One way is to use the HEAD request, which asks for HTTP Header of the response only. I know in HEAD responses, the size of the body is included. But I don't know if there anything available for size of images.

Saeed Neamati
  • 35,341
  • 41
  • 136
  • 188
  • 2
    I'm not sure that the dimensions of an image is in the HEAD response, and anyway, you could only do this on `same-origin` request, or if you specifically setup your server to allow `cross-origin`. – vsync Jun 26 '14 at 10:47