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!
By Ben Kol September 21, 2011 - 6:59 pm
Under the setTimeout’s anonymous function, $(this) points to the containing function and no to the image.
Change the comment under setTimeout to:
// do something based on $(‘img’).width and/or $(‘img’).height
BTW, you saved me.
By Andrew Ramsden October 16, 2011 - 10:46 pm
Thanks Ben Kol, well spotted!
By Larry Ahmeen January 25, 2015 - 10:29 pm
This was the one for me. Spent hours on SO, but this was the solution that saved me. Thanks!