Get image dimensions with Javascript before image has fully loaded

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="https://stackoverflow.com/questions/6575159/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'); }

Leave a Comment