$ ('img'). load () is firing too early

I am trying to get the proportions of images using their load () methods.

$('img').load(function(){
    alert(this.src);
    alert($(this).width());
    setAspectRatio(this);
});

(this.src) tells me what I expect to hear. ($ (this) .width ()) gives me 0.

I found this in the documentation for load ():

Download event warnings when used with images

A common problem that developers are trying to solve with the .load () shortcut is to execute a function when the image (or collection of images) is fully loaded. There are several notable reservations with this that should be noted. It:

  • It does not work consistently and not reliably, cross browser
  • In WebKit, it does not work correctly if the same src is set for the src image as before.
  • Incorrectly inverts the DOM tree
  • , .

, get(), , - .

, Google . - ?

+5
4

$(window).load(function(){  
  //initialize after images are loaded  
});  

, . , , script .

+1

$('<img/>').load(function(){ });
+1

This answer also applies to this question. Your code will not work on cached images, because when the images are already cached, the load event usually fires before the callback is bound. The code in the linked answer solves this problem.

0
source

Have you tried the following

   $('img').load(function() {
      alert(this.src);
      alert($(this).width());
      setAspectRatio(this); }).delay(500);​
0
source

All Articles