Kawd
Kawd

Reputation: 4450

How do I check if an already loaded image has loaded in JavaScript?

I'm not referring to either :

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

or :

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

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

If #someimage has already loaded by the time one of the above functions is called, the function will fail to execute.

I could create an interval that keeps checking the height and width of the image and as soon as none of them is equal to zero then consider the image as having loaded :

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

I've tried this and it fails to work having obviously evaluated the height and width of the image before they reach their maximum value.

I could check whether the height and width of the image is the correct one but I might not know the height and width of an image in advance. I also want to avoid using magic numbers.

Any suggestions?

Thanks!

Upvotes: 4

Views: 7566

Answers (1)

LavenPillay
LavenPillay

Reputation: 165

I think you're looking for the solution provided here :

How to tell if an image is loaded or cached in JQuery?

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

Upvotes: 3

Related Questions