5

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?

Community
  • 1
  • 1
Patrick
  • 51
  • 2
  • Why can't you include the `width` and `height` attributes on your `` elements? The "It doesn't work consistently nor reliably cross-browser" caveat pretty much means "don't try this". – mu is too short May 05 '11 at 04:47
  • Come to think of it, I hadn't even considered that. I'd prefer a solution that doesn't require additional markup, but this will definitely work, which is great. Thanks! – Patrick May 05 '11 at 04:59
  • Always include the `width` and `heigh` attributes on your images, it neatly does away with a lot of confusion, timing issues, and other problems. – mu is too short May 05 '11 at 05:09

4 Answers4

1

try using this

$('<img/>').load(function(){ });
j0k
  • 22,600
  • 28
  • 79
  • 90
stannesi
  • 21
  • 3
1

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.

Chris Rogers
  • 1,773
  • 1
  • 15
  • 18
  • Unfortunately, since the images are entering the page through get(), they don't exist yet when the window loads. – Patrick May 05 '11 at 05:36
0

have you tried the following

   $('img').load(function() {
      alert(this.src);
      alert($(this).width());
      setAspectRatio(this); }).delay(500);​
Denzil Sequeira
  • 129
  • 3
  • 7
0

This answer also relates to this question. Your code won't work on cached images because when images are already cached the load event usually fires before the callback binding is made. The code in the linked answer solves that problem.

Community
  • 1
  • 1
uɥƃnɐʌuop
  • 14,022
  • 5
  • 58
  • 61