You can switch the calls to .html() and .onload() .
If the image is loaded from the cache, I assume that the .html() call completes before the script was able to associate the function handler with the onload event image, therefore, bypassing the loading event itself (since the image is already loaded ).
If it is still loading the image (i.e. not cached), there will be enough time to call .onload attach before the image completes rendering.
While you're on it, you can do it in a jQuery way, so you add events more like DOM2 than DOM0.
var image = $('<img/>', { src : 'http://mydomain.com/image.png' }).load(function () { alert(this.width); })
If we need to install src after onload , we could also do this instead:
var image = $('<img/>') .load(function () { alert(this.width); }) .attr('src','http://mydomain.com/image.png') .appendTo(container) ;
Hope this works cleanly.
source share