title: Wait for image to be loaded before going on
body: <p>I'm developing a game using JavaScript and <code>canvas</code>. As the game loads, all images that will be used are being cached.</p>
  
  <p>Observing the resource timeline, I see that the following code triggers an asynchronous request:</p>
  
  <pre><code>var sprite = new Image();
  sprite.src = "sprites/sheet1.png";
  </code></pre>
  
  <p>The engine will keep executing, eventually beginning to draw and play the level. Images that are loaded after the first frame is painted might never appear due to clipping (i.e. not getting "dirty").</p>
  
  <p>So I tested the following:</p>
  
  <pre><code>console.log("begin");
  var sprite = new Image();
  sprite.onload = function() { console.log('loaded!'); };
  sprite.src = "sprites/sheet1.png";
  console.log("end");
  </code></pre>
  
  <p>The resulting console outputs in the order they occur are:</p>
  
  <ul>
  <li><code>begin</code></li>
  <li><code>end</code></li>
  <li><code>loaded!</code></li>
  </ul>
  
  <p>I'm looking for a similar way to <code>$.ajax</code> with <code>async: false</code> to perform the loading. Can't figure out how... thanks in advance for you help!
  J.</p>