4

I know there's a load() event in jQuery which is triggered when the image has finished loading. But what if the event handler is attached after the image has finished loading?

Is there a property like $('#myimage').isLoaded() to check if the image is already loaded?

laurent
  • 88,262
  • 77
  • 290
  • 428
  • i think this is exactly what you need : [http://stackoverflow.com/a/1257418/235710](http://stackoverflow.com/a/1257418/235710) – Adil Shaikh Jul 07 '12 at 08:37

3 Answers3

10

You can check the complete property of the image.

Is there a property like $('#myimage').isLoaded() to check if the image is already loaded?

Nope, but you could make it so :)

jQuery.fn.isLoaded = function() {
    return this
             .filter("img")
             .filter(function() { return this.complete; }).length > 0;
};

This would produce true if all images in the collection have been loaded, and false if one or more images were not. You could adapt it to suit your needs.

alex
  • 479,566
  • 201
  • 878
  • 984
  • '.complete' is actually pretty widely supported. It's been standardized in HTML5, but supported long before that (even IE6, I believe). – jfriend00 Jul 07 '12 at 08:58
2

Plain JS in enough. Image object has complete property. Check it out here: http://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_img_complete

sleepwalker
  • 1,032
  • 1
  • 9
  • 15
1

Its a little bit hackish and I am not sure it will work everywhere. Do test at your own.

$.fn.isLoaded = function(message) {
  var $this = $(this);
  if($this.height() > 0 && $this.width() > 0){
     return true;
  }
  return false;
};

$('#myimage').isLoaded()

EDIT:

This works in ff and chrome,

$.fn.isLoaded = function(message) {
  var $this = $(this); 
  $this.hide();   // becaues firefox gives a 24*24 dimension
  var w = this[0].width;
  var h = this[0].height;  
  $this.show(); 
  if(w > 0 || h > 0){ 
    return true;
  } 
  return false;
}; 
console.log($('#myimage').isLoaded());

but if you hide the image ie gives 0 as width and height, so it fails for ie. For ie, you shouldnt hide the image.

I hope, somebody can combine both these features to make a cross browser thing or atleast it will help somebody for sure.

Jashwant
  • 28,410
  • 16
  • 70
  • 105
  • This will only work for images that are on the page and displayed. Use `this[0].height` and `this[0].width` instead (which are set to the image dimensions if the image is loaded) – Esailija Jul 07 '12 at 08:46
  • strange but it gives a 24x24 dimension on firefox. Works fine in chrome. I guess the 24*24 is the size of image which shows when no image is found. – Jashwant Jul 07 '12 at 09:01
  • 2
    True, both of these solutions are pretty crappy – Esailija Jul 07 '12 at 09:01