Nav & Search

Width and Height of Dynamically Loaded Images in Webkit


Another day, another problem and (luckily) a new solution when developing the next version of Lumebox. It seems as if Webkit browsers sets the image height and width before the image file has been loaded which means that when using, for example, jQuery the .loaded()-event is fired when the height is still 0. Stackoverflow was kind enough to pin down the problem in these two Q&As, but the given solutions didn’t really fix the problem.

The easiest way to solve the it is to use


instead of


or to set the height and width attributes of the img-element but that only works for static documents. To load the images I use a helper function that triggers a callback function when the image is loaded

loadImage: function(src, callback){
  $("<img alt="" />").attr("src", src).load(callback);

What I found out was that when the callback function is fired most jQuery functions report the width as 0  (such as width(), outerWidth() etc) both on the image itself and any other DOM-elements surrounding it in Webkit (it works just fine in IE6+, FF and so on). However,  this.width inside the .load() and callback (which fires when the image file has been loaded and inserted into the document) returns the width of the actual image element. Using this we can set the HTML-attributes manually inside the callback

  id: img,
  width: this.width,
  height: this.height

and Webkit now uses these to report the size rather than it’s own measurements (which isn’t finished at this stage) so that we then can get the actual width of the image using

var contentWidth = $("#img").attr("width");

Using the Lumebox code as a base I’ve pieced together a complete (but simplified) example of what I use there

function loadImage(item, callback){
	$("<img alt="" />").attr("src",;

var lumeboxItem = {link: ""};

loadImage(lumeboxItem, function() {
		"class": "lumebox-img",
		width: this.width,
		height: this.height
	$("body").append(this).find("img.lumebox-img").wrap('<div class="post"><div class="post-body"></div></div>');

2 thoguhts on “Width and Height of Dynamically Loaded Images in Webkit

Rockadix says 2010-11-12:

could you make a full demo pls

thanks so much!

Anonymous says 2010-11-15:

Yes! I’ve updated the post above with a complete example at the end. Please let me know if something isn’t clear enough.

Leave a comment

Your email will not be published.