title: How to prevent a background image flickering on change
body: <p>I'm applying a repeated background image from a canvas to a div via javascript like this:</p>
  
  <pre><code>var img_canvas = document.createElement('canvas');
  
  img_canvas.width = 16;
  
  img_canvas.height = 16;
  
  img_canvas.getContext('2d').drawImage(canvas, 0, 0, 16, 16);
  
  var img = img_canvas.toDataURL("image/png");
  
  document.querySelector('#div').style.backgroundImage = 'url(' + img + ')';
  </code></pre>
  
  <p>I have to update it quite frequently. The problem is it flickers upon change, it doesn't appear to happen in Chrome but it's really bad in Firefox and Safari. Is it possible to stop this? I didn't think it would happen since it's a dataurl and therefore doesn't need to be downloaded.</p>
  
  <p><strong>Solution:</strong></p>
  
  <pre><code>// create a new Image object
  var img_tag = new Image();
  
  // when preload is complete, apply the image to the div
  img_tag.onload = function() {
  
      document.querySelector('#div').style.backgroundImage = 'url(' + img + ')';
  }
  
  // setting 'src' actually starts the preload
  img_tag.src = img;
  </code></pre>