title: Should setting an image src to data URL be available immediately?
body: <p>Consider the following (fragile) JavaScript code:</p>
  
  <pre><code>var img = new Image;
  img.src = "data:image/png;base64,..."; // Assume valid data
  
  // Danger(?) Attempting to use image immediately after setting src
  console.log( img.width, img.height );
  someCanvasContext.drawImage( img, 0, 0 );
  
  // Danger(?) Setting onload after setting src
  img.onload = function(){ console.log('I ran!'); };
  </code></pre>
  
  <p><strong>The Question(s)</strong></p>
  
  <ul>
  <li>Should the image width and height be correct immediately?</li>
  <li>Should the canvas draw work immediately?</li>
  <li>Should the <code>onload</code> callback (set after the src was changed) be invoked?</li>
  </ul>
  
  <p><strong>Experimental Tests</strong><br>
  I created a <a href="http://phrogz.net/tmp/img_via_dataurl.html" rel="noreferrer">simple test page</a> with similar code. In Safari my first tests, both by opening the HTML page locally (<code>file:///</code> url) and loading it from my server, showed everything working: the height and width is correct, the canvas draw works, <em>and</em> the <code>onload</code> also fires.</p>
  
  <p>In Firefox v3.6 (OS X), loading the page after launching the browser shows that the height/width is not correct immediately after setting, <code>drawImage()</code> fails. (The <code>onload</code> handler does fire, however.) Loading the page again, however, shows the width/height being correct immediately after setting, and <code>drawImage()</code> working. It would appear that Firefox caches the contents of the data URL as an image and has it available immediately when used in the same session.</p>
  
  <p>In Chrome v8 (OS X) I see the same results as in Firefox: the image is not available immediately, but takes some time to asynchronously 'load' from the data URL.</p>
  
  <p>In addition to experimental proof of what browsers the above does or does not work, I'd really love links to specs on how this is supposed to behave. So far my Google-fu has not been up to the task.</p>
  
  <p><strong>Playing It Safe</strong><br>
  For those who don't understand why the above might be dangerous, know that you should use images like this to be safe:</p>
  
  <pre><code>// First create/find the image
  var img = new Image;
  
  // Then, set the onload handler
  img.onload = function(){
    // Use the for-sure-loaded img here
  };
  
  // THEN, set the src
  img.src = '...';
  </code></pre>