44

I have some code I am trying to run once my image has finished loading. I use this following jQuery code:

$("#myimageid").load(function() {
    alert('Image Loaded');
});

However the popup never show up. I can't get the .load() function to work ! Anyone had issues with this?

1
  • Where exactly have you placed that code?
    – Pointy
    Aug 27, 2010 at 21:04

2 Answers 2

116

If you're running this after the image already has a set source, you need to do an additional check for caches images (who fired the event, just before you added an event handler listening for it). You can do that like this:

$("#myimageid").on('load', function() {
  alert('Image Loaded'); 
}).each(function() {
  if(this.complete) $(this).load();
});

Update for later versions of query, use:

if(this.complete) $(this).trigger('load');

Using (this).load(); will produce a Cannot read property 'indexOf' of undefined error

15
  • That worked ! Thanks mate $(document).ready(function() { $("#googleimage").load(function() { alert('Image Loaded'); }).each(function() { if (this.complete) $(this).load(); }); }); Aug 30, 2010 at 12:50
  • 2
    nice, why was this so hard to find!
    – Dominic
    Sep 18, 2012 at 9:56
  • 1
    Worth noting .complete is not defined by jQuery but on the DOM element itself. Therefore $(selector).complete == undefined so you might want unwrap it $(selector)[0].complete. The answer implies this as $.each assigns raw DOM elems as this but I got confused for a wild moment :)
    – nuala
    Mar 26, 2014 at 13:10
  • 1
    @yoshi is correct. I believe $(selector).prop("complete") should also work.
    – sam
    May 26, 2016 at 19:39
  • 4
    In jquery 3 if(this.complete) $(this).trigger('load');
    – Artem P
    Mar 31, 2017 at 12:55
0

What happens when you clear your browser's cache and try the script again? From the jQuery load() docs:

It is possible that the load event will not be triggered if the image is loaded from the browser cache. To account for this possibility, we can use a special load event that fires immediately if the image is ready. event.special.load is currently available as a plugin

In general, it is not necessary to wait for all images to be fully loaded. If code can be executed earlier, it is usually best to place it in a handler sent to the .ready() method.

So it sounds like your cached image isn't triggering the load event, so you may want to try the plug-in that's mentioned. You can find the JS file to download here.

Hope this helps!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.