Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

$('img').load() firing too soon

Tags:

jquery

I'm trying to get some images' aspect ratios 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():

Caveats of the load event when used with images

A common challenge developers attempt to solve using the .load() shortcut is to execute a function when an image (or collection of images) have completely loaded. There are several known caveats with this that should be noted. These are:

  • It doesn't work consistently nor reliably cross-browser
  • It doesn't fire correctly in WebKit if the image src is set to the same src as before
  • It doesn't correctly bubble up the DOM tree
  • Can cease to fire for images that already live in the browser's cache

A couple of those items sound a little vague to me, but these images were appended into an element using the get() method, so my best guess is that my problem has something to do with that.

This doesn't seem like an unusual circumstance, but Google isn't giving me anything. Has anybody here encountered this?

like image 982
Patrick Avatar asked Nov 04 '22 22:11

Patrick


2 Answers

Have you tried using

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

This will not trigger until the page has finished coming down. You could then grab whatever img's you want and use your script on them.

like image 100
Chris Rogers Avatar answered Nov 14 '22 20:11

Chris Rogers


try using this

$('<img/>').load(function(){ });
like image 25
stannesi Avatar answered Nov 14 '22 21:11

stannesi