Search code examples
javascriptimageloadingdimensions

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.


Solution

  • 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'); }