Question

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?

Was it helpful?

Solution

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.

OTHER TIPS

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

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top