title: Wait for image loading to complete in JavaScript
body: <p>I'm loading images with JavaScript. Something like this:</p>
  
  <pre><code>images[0]=new Image();
  images[0].onload=function(){loaded++;console.log(loaded)};
  images[0].src="assets/img/image.png";
  </code></pre>
  
  <p>When I look at the log, I see that all the images are loaded nicely, since the value of the "loaded" variable increases with each loaded image.</p>
  
  <p>However I would like to stop any further action to be executed until this amount reaches it's maximum, so right after setting up the images, I place a while cycle.</p>
  
  <pre><code>while(loaded&lt;11){
      document.getElementById("test").innerHTML="Loading "+loaded+"/11";
      console.log(loaded);
  }
  //Some code here which should only run after everything has been loaded
  //In other words: when the statement in the while cycle becomes false
  </code></pre>
  
  <p>However my browser simply crashes, since the while seems to be stuck in an infinite loop. When I check the log, I see that "0" was written 1000 times, and after that, the numbers from 1 to 11 (which implies that the images in fact gets loaded, but the while does not care about it, and crashes faster than it could happen).</p>
  
  <p>I believe that the method I'm trying to use here is not the right approach to solve this problem.</p>
  
  <p>How can I put everything on hold until every asset which is needed for the site is loaded?</p>