Allan
Allan

Reputation: 211

Retrigger $().load event in jQuery

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

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

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?

Upvotes: 0

Views: 660

Answers (2)

Allan
Allan

Reputation: 211

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');
});

Upvotes: 1

Nick Craver
Nick Craver

Reputation: 630549

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
});

Upvotes: 2

Related Questions