Last Updated: February 25, 2016
·
10.57K
· dimsemenov

Get image size before it's fully loaded

I was looking for a way to get an image size with JavaScript before it's completely loaded. It's useful, for example, when you want to display it progressively.

I've figured out that we can just fire an interval that will run until an image has defined width. Here is how it works:

(view it on GitHub if you don't like how code is highlighted here :)

// detect if naturalWidth property is supported
    // getting it is much faster then getComputedStyle()
var supportsNatural = ( "naturalWidth" in (new Image()) ),
    imagePath = 'image.jpg',
    interval,
    hasSize,
    onHasSize = function() {
        if(hasSize) return;

        var naturalWidth = supportsNatural ? img[0].naturalWidth : img.width();
        var naturalHeight = supportsNatural ? img[0].naturalHeight : img.height();

        clearInterval(interval);
        hasSize = true;
    },
    onLoaded = function() {
        onHasSize();
    },
    onError = function() {
        onHasSize();
    },
    checkSize = function() {

        if(supportsNatural) {
            if(img[0].naturalWidth > 0) {
                onHasSize();
            }
        } else {
            // some browsers will return height of an empty image about 20-40px
            // just to be sure we check for 50
            if(img.width() > 50) {
                onHasSize();
            }
        }

    },
    img = $('<img/>')
        .on('load', onLoaded)
        .on('error', onError)
        .attr('src', imagePath) 
        .appendTo(someContainer);

interval = setInterval(checkSize, 100);
checkSize();

Hope it helps someone! – @dimsemenov