how to check if image loaded or not in javascript?

how to check if image loaded or not in javascript?

If you are having a webpage with large sized images, you would notice the browser taking long time to load those images and showup. A good idea would be show a loading animation until large photos load.

There is a way to check whether the images have been loaded or not in javascript. Using the Image() object is a good method to cache large images.

You can use onload function to trigger a event after loading is complete.

objImg = new Image();
objImg.src = 'photo.gif';
objImg.onload = function() { 
                           /// do some work;
                        }

Another way of checking is use complete property

objImg = new Image();
objImg.src = 'photo.gif';

if(!objImg.complete)
 { 
        /// do other work;
             }

Hope this helps if you are a javascript programmer.

Similar Posts:

Tags:

Balakrishnan Prabhu

Mr. Balakrishnan Prabhu is the founder of Corpocrat magazine. He is also the founder of Best Citizenships (BC), assisting wealthy individuals with with global citizenship and residency programs in Europe. His other interests are Linux, Machine learning, Wordpress, etc. You can contact him here

  • Nightfly

    Not all browsers support onload or complete. For complete cross-browser compatibility, check if the width or height are greater than 0.

  • Gaurav Arya

    Awesome code of Java Script. Thanks for letting us know.
    I also thought to mention one very minor thing here. In the code above
    objImg.onload = function {
    /// do some work;
    }

    Parenthesis “()” should be added after the keyword “function” above. I know almost everybody is aware of it eventhen thought to mention it here.

    Many thanks for this great help.

    Gaurav Arya

  • http://www.best-php-scripts.com pbu

    very well spotted Gaurav!

  • http://jurius.name/ Jurius

    You have to put onload event handler declaration before src property change because IE wouldn`t process it well.

  • http://www.cheapestghdsuk.co.uk cheapest ghds

    Thanks for your submission. I also believe laptop computers have become more and more popular lately, and now are sometimes the only form of computer employed in a household. The reason being at the same time that they’re becoming more and more reasonably priced, their processing power keeps growing to the point where these are as powerful as pc’s coming from just a few years ago.

  • http://www.10pixel.com Ashish

    I don’t think this works at all. You must get the size of the image in KB and then you need to check if the total size is downloaded or not.

    I think this will work to check if IMAGE is downloaded or not completely in JavaSript. If somebody can do this, please let me know… LOL

    thanks!!