Search code examples
javascriptjqueryimageloaded

Check if an image is loaded in jQuery (or plain JavaScript)


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?


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.