How to find async Image status in an Sync Javascript

128 views Asked by At

I am loading the image in the JS and waiting for its status on its onload event. I have JS file included with source in the HTML, and want to know the status of the image loaded initially using JS.

Example:

<html> <head> <script> var imgStatus = false; var img = new Image(); img.onload = function(){ imgStatus = true; } img.src = "http://mydomains.com/someimage.jpg"; </script> </head> <body> <script type="text/javascript" src="js1.js"></script> </body> </html>

The code for js1.js is

window.onload = function(){ // check for imgStatus = true and then only do something // till then do nothing }

Do I need to constantly check the value of imgStatus using setInterval or is there any other better way of waiting till the status is known.

2

There are 2 answers

0
Furqan Zafar On

The easiest way would be to fire an event when the imgStatus is true for example:

img.onload = function(){
 imgStatus = true;
 $(window).trigger("img/ready");
};

function doSomething(){
 alert("image is ready");
};

window.onload = function(){
 if (imgStatus)
  doSomething();
 else
  $(window).bind("img/ready", doSomething);     
}
0
Kaustav On

This is a possibility (deprecated since jQuery 1.8) - http://api.jquery.com/load-event/