How to check if an already loaded image is loaded in JavaScript?

I do not mean:

var img = document.getElementById('someimage');
img.onload = function () {.....};

      

or:

$("#someimage").load(function (){...});

      

Please correct me if I am wrong , but I believe that both of the above options only work if the image has not been loaded yet by the time any of these functions are called.

If #someimage

already loaded by the time one of the above functions is called, the function will fail.

I could create a spacing that will check the height and width of the image, and once none of them are zero, consider the image as loaded:

var checkImg = setInterval (function ($img, cb)
{
   if (($img.height() > 0) && ($img.width() > 0))
   {
      clearInterval(checkImg);
      cb();
   }
}, 200);

      

I tried this and it doesn't work by explicitly evaluating the height and width of the image before it reaches its maximum value.

I could check if the height and width of the image were correct, but I might not know the height and width of the image beforehand. I also want to avoid using magic numbers

.

Any suggestions?

Thank!

+3


source to share


1 answer


I think you are looking for the solution suggested here:

How do I know if an image has been loaded or loaded in JQuery?



Basically, check the ".complete" property of the image object.

+2


source







All Articles