jQuery load event not firing on images

Hi all! Have any of you ever tried to use the jquery .load() method only to have it work sometimes and not others? Well I have had it happen to me quite a few times and usually my solution was to use the setTimeout() method to trigger the load event on the image after say 0.3 seconds.

Now, the issue with doing this is that if the .load() method is fired correctly, the setTimeout() method will still be called meaning that the load event would be fired twice, which isn’t really what we want now is it?

So after having this issue quite a few times I finally decided to Google around a bit and see if I could find a better solution than the quite frankly poor solution that I was currently using.

After about 20 minutes of searching through Google, I found quite a good solution in the comments for the jQuery .load() method documentation (link here).

Normally you would do something like this:

$('.imageSelector').load(function(){
  //Do Something...
});

This issue with doing it this way is that sometimes the load event will not always be triggered (usually when the image is being loaded from the cache), I suspect the reason for this is because the image is being loaded too quickly meaning that the image has finished loading before the event has actually been attached to it.

Usually you won’t get this problem the first time you load an image because the image has to be downloaded first which gives jQuery time to attach the event before it has finished downloading. Where as if the image has already been downloaded and it is in the cache, it will sometimes have finished loading before the event has been attached.

I have slightly modified the solution found on the jQuery page as follows:

$('.imageSelector').load(function(){
  //Do Something...
}).each(function(){
  if(this.complete) {
    $(this).trigger('load');
  }
});

This snippet of code does the same thing as the first snippet but at the same time as adding an event listener onto the image it also checks to see if the image has already finished loading. If the image has finished loading, it triggers the load event that has just been added to the image.

Well, I hope this quick tip has helped.

Thanks for reading 🙂

Mike.