Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Image width traces zero with onload when cached

I'm building a Javascript lightbox and I'm trying to adjust the size once the image has loaded. I'm using the code below, which works fine - it outputs the correct width once loaded.

My problem:

When I refresh, it will load the image instantly from the cache, and it seems to bypass the load. I get an instant zero for the width. Why does this happen?

My code:

var oImage = new Image();

oImage.src = 'http://mydomain.com/image.png';

container.html(oImage);

oImage.onload = function(){

    alert(this.width);
}

** Update **

@Alex: This is the code I've tried with your plugin, I assume I'm probably doing something wrong. I'd be eager to get this working because your plugin looks quite good.

container.waitForImages(function() {

    var cWidth = $(this).width();

    alert("width: "+cWidth); // returns 0 - works first time but not cached

});

// Adding the image to the container for preload

container.html('<img src="mygraphic.png" />');
like image 746
JCraine Avatar asked Dec 21 '22 02:12

JCraine


1 Answers

You need to do a few things...

  • Check the complete property of the img element.
  • Attach the load event before setting the src property.

Also, I found creating a new Image and assigning the src there is the best way to determine if the image has loaded or not.

like image 184
alex Avatar answered Jan 02 '23 00:01

alex