jQuery or Javascript check if image loaded

I usually do this:

var image = new Image();
image.onload = function () {
   console.info("Image loaded !");
   //do something...
}
image.onerror = function () {
   console.error("Cannot load image");
   //do something else...
}
image.src = "/images/blah/foo.jpg";

Remember that the loading is asynchronous so you have to continue the script inside the onload and onerror events.


In the case of waiting of loading multiple images:

var images = $("#div-with-images img");
var unloaded = images.length;
images.on('load', function(){
  -- unloaded;
  if (!unloaded) {
    // here all images loaded, do your stuff
  }
});

I would give the images that require this constraint a class like mustLoad where:

<img class="mustLoad" src="..." alt="" />

and then create a generic image load handler function, such as:

$('img.mustLoad').on('load',function(){
        /* Fire your image resize code here */
});

Edit:

In response to your comments about deprecating .load() above, .load() was deprecated, in favor of .on('load') to reduce ambiguity between the onLoad event and Ajax loading.


There's also a useful .complete property of an image object, you can use it if you have already set the .src of your <img> before attaching to it any event listeners:

var img=document.getElementById('myimg');
var func=function(){
    // do your code here
    // `this` refers to the img object
};
if(img.complete){ 
    func.call(img);
}
else{ 
    img.onload=func; 
}

Reference: http://www.w3schools.com/jsref/prop_img_complete.asp