Cached images have no width or height in webkit (e.g. Chrome or Safari)

Stackoverflow (SO) has always been a handy resource. Today I noticed a particularly valuable comment with 0 votes.

I created an SO account with the explicit purpose of voting this comment upwards, but unfortunately, I have no reputation on SO, and am not able to do this (yet).

For lack of a better way to credit JKS for his insightful solution I thought I’d recognise it here.

Problem

In webkit browsers (e.g: Chrome or Safari) the onload event fires for both cached and non-cached images, but images loading from cache seem to return dimensions of 0—for both width and height.

Solution

JKS proposes a simple solution, a seemingly redundant setTimeout before taking your measurements seems to magically restore cached image dimensions. In jQuery, that would look like this:

$('img').load(function(){
    setTimeout(function(){
        // do something based on $('img').width and/or $('img').height
    }, 0);
});

Thanks

Thanks again to JKS for the tip!

Posted in

3 Responses to "Cached images have no width or height in webkit (e.g. Chrome or Safari)"

Leave a reply