views:

133

answers:

2

Hey.

When I want something to happen when an image is loaded I use

$("#image").load(function() { something });

  • but in anything other than Firefox this works only the first time the image gets loaded. For instance if I have made a gallery of images and want something to happen when an image is loaded I use .load and it works the first time: but if user shuffles back to the image (that's already in cache) the event does not trigger in Opera, IE etc.

One way to fix this is to add some random number to the image src, but this takes up extra bandwidth because it has to download the image again (right?).

Are there any good solutions for this?

+1  A: 

Use the .complete check:

$("#image").each(function() {
  if(this.complete) doSomething(); //Runs immediately, image ready (cached)
  else $(this).load(function() { doSomething(); }); //Will run when loaded
});
Nick Craver
I think this will work. Thanks!
Allan
+1  A: 

I'll actually add another way:

This was not made by me, unfortunately I do not know the original brain behind this:

$('#image').one('load',function() {
 so_something();
}).each(function() {
 if(this.complete) $(this).trigger('load');
});
Allan