title: Swap an image without flicker while showing the new one immediately
body: <p>TL;DR: Is there a way to swap the images reliably while showing whichever image is being loaded at the time without causing page flicker?</p>
  
  <hr>
  
  <p>I have 2 images and 2 buttons and when I hover over one button it shows the one image. Hovering over the other button swaps to the second image. I was doing it like this:</p>
  
  <pre class="lang-js prettyprint-override"><code>$('#button1').mouseover(function() {
      $('#image').attr('src', 'image1.png');
  });
  
  $('#button2').mouseover(function() {
      $('#image').attr('src', 'image2.png');
  });
  </code></pre>
  
  <p>This works fine but when the first image has loaded and the second hasn't, it doesn't show the second image until it has completed loading. To try to give the user some indication of when the new image is loading (which they're expecting to appear immediately), I forced it to add a null image before these swaps, like this:</p>
  
  <pre class="lang-js prettyprint-override"><code>$('#button1').mouseover(function() {
      $('#image').attr('src', '#');
      $('#image').attr('src', 'image1.png');
  });
  
  $('#button2').mouseover(function() {
      $('#image').attr('src', '#');
      $('#image').attr('src', 'image2.png');
  });
  </code></pre>
  
  <p>This works great when one image is loading by showing the image as it's loading but now once both are loaded, the null image in between them causes a flicker when switching images. I thought I could fix this by turning the null image off once both images are loaded but that has turned out to be unreliable. Both <code>$('#image').prop('complete')</code> and <a href="https://github.com/desandro/imagesloaded" rel="nofollow">imagesloaded</a> as suggested in other locations on stackoverflow are inconsistent at noticing whether the image has been loaded or not. Detecting loaded images just seems to be a dead end.</p>
  
  <p>I also considered trying to force the images to show and hide before and after they were created but this doesn't seem to work at all though I'm not sure why. The new one doesn't show while loading and I'm not sure if they're swapping properly:</p>
  
  <pre class="lang-js prettyprint-override"><code>$('#button1').mouseover(function() {
      $('#image').hide();
      $('#image').attr('src', 'image1.png');
      $('#image').show();
  });
  
  $('#button2').mouseover(function() {
      $('#image').hide();
      $('#image').attr('src', 'image2.png');
      $('#image').show();
  });
  </code></pre>
  
  <p>Is there a way to swap the images reliably while showing whichever image is being loaded at the time without causing page flicker that I haven't tried?</p>