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?

1

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

1 Comment

'.complete' is actually pretty widely supported. It's been standardized in HTML5, but supported long before that (even IE6, I believe).
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

Comments

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.

3 Comments

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)
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.
True, both of these solutions are pretty crappy

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.