Detect image load

Is it possible to detect once an image has been loaded with jQuery?


You can use the .load() event handler, like this:

$("#myImg").load(function() {
  alert('I loaded!');
}).attr('src', 'myImage.jpg');

Be sure to attach it before setting the source, or the event may have fired before you attached a handler to listen for it (e.g. loading from cache).

If that's not doable (setting the src after binding), be sure to check if it's loaded and fire it yourself, like this:

$("#myImg").load(function() {
  alert('I loaded!');
}).each(function() {
  if(this.complete) $(this).load();
});

It's just as simple to use plain Javascript:

  // Create new image
var img = new Image();

  // Create var for image source
var imageSrc = "http://example.com/blah.jpg";

  // define what happens once the image is loaded.
img.onload = function() {
    // Stuff to do after image load ( jQuery and all that )
    // Within here you can make use of src=imageSrc, 
    // knowing that it's been loaded.
};

  // Attach the source last. 
  // The onload function will now trigger once it's loaded.
img.src = imageSrc;