How do we detect image loading finished on our webpage?
<p>I want to put images into a marquee scrolling text. As the marquee text function will need to detect the length of the items (text and images) that it is scrolling before it start scrolling. This can only be done when the image had been loaded onto the page which will take some time because my image is from a server. So, I need to know when does the image had been finish loaded so that I can start scrolling.</p>

<p>Below is the image finish loading detection javascript that I'm using now. I'm using socket.io to receive the images info:</p>

<pre><code>  var images_expected = 0;
  socket.on('res-displaySetting', function(display){
      images_expected = display.runningText.length;
      $('.marquee').marquee('destroy');
      var html = "";
      for(var k=0; k &lt; display.runningText.length; k++)
      {
          if ((display.runningText[k].image == "") &amp;&amp; (display.runningText[k].message == "")) 
          {
              images_expected--;
              continue;
          }
          else if (display.runningText[k].image == "")
          {
              html += display.runningText[k].message;
              images_expected--;
          }
          else if (display.runningText[k].message == "")
              html += " &lt;img src='" + serverIP + "/img/" + display.runningText[k].image + "'&gt; ";
          else
              html += " &lt;img src='" + serverIP + "/img/" + display.runningText[k].image + "'&gt; " + display.runningText[k].message;
      }
      $('.marquee').html(html);

      if (html != "") initMarquee(); 
  });

  function initMarquee() {
    interval = window.setInterval(checkImagesLoaded, 1000);  
  }

  function checkImagesLoaded() {console.log("checking");
      if ($('.marquee img').length === images_expected) {
          clearInterval(interval);
          setTimeout(startMarquee); 
      }
  }

  function startMarquee() {
    $('.marquee').marquee({duration: 8000});  
  }
</code></pre>

<p>There is a checkImageLoad() function to check whether the image had been loaded. It will check for 1 second. After that the marquee scrolling text will start. Sometimes the image will loaded out but sometimes the image will not load out but just show a square empty box.</p>

<p>I try to increase the checking time to 5 seconds or 10 seconds also no use. Sometimes it just won't load out. I think it consider the square empty box as the image already loaded.</p>

<p>What do you guys think? Is there a better way to detect image finish loading?</p>