user828591 user828591 - 1 year ago 186
Javascript Question

Get image dimensions with Javascript before image has fully loaded

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.

Answer Source

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

Here's a solution JavaScript (demo):

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

img.onload = function () { loaded = true; };
img.src = 'some-image.jpg';

var wait = setInterval(function () {
    if (loaded) {
    } else {
        console.log(img.naturalWidth, img.naturalHeight);
}, 0);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download