title: Preloading Images using base64
body: <p>I have made a 'drag and drop' file upload utility for my users. I made an upload progress bar out of 13 PMG images and animated it using jQuery. That is working quite well if the user just drops one or two files at the same time. But I noticed that if the user drops 10 files the browser makes a request for every image (130 requests). Sometimes the browser takes these images from cache, but sometimes not. So, my solution was to preload the images like this:</p>
  
  <pre><code>function preload()
  { 
      // create object
      imageObj = new Image();
  
      // set image list
      images = new Array();
      images[0]="img/ProgressBarContent.png";
      images[1]="img/ProgressbarEndEffect.png";
      images[2]="img/0.png";
      images[3]="img/1.png";
      images[4]="img/2.png";
      images[5]="img/3.png";
      images[6]="img/4.png";
      images[7]="img/5.png";
      images[8]="img/6.png";
      images[9]="img/7.png";
      images[10]="img/8.png";
      images[11]="img/9.png";
      images[12]="img/percentIcon.png";
      images[13]="img/ProgressBar.png";
  
      // start preloading
      for(var i = 0; i &lt; images.length; i++) 
      {
          imageObj.src=images[i];
  
          if(i == (images.length-1))
          {
          //preloading done, give a visual feedback and droping functionality can be activated 
          hideLoadingOverlay();
          }     
       }
   }
  </code></pre>
  
  <p>But that did not made any difference.<br>
  So I thought I could let a PHP script read the images I need, encode them as base64 and output them as a JavaScript array like this:</p>
  
  <pre><code>$file= base64_encode( file_get_contents ( 'img/0.png') );
  echo 'images["img/0.png"] = "data:image/png;base64,'.$file.'";';
  </code></pre>
  
  <p>That way I could also "hardcode" the images directly into my HTML, right?<br>
  I thought that in JavaScript I could do this:</p>
  
  <pre><code>$(".selector").attr("src", images['filename']);
  </code></pre>
  
  <p>Is this a good solution? Or is there a "proper"/better way?</p>
  
  <p>Thanks!</p>
  
  <p>EDIT:
  It does not matter if old browsers do not support this. The scripts are used for a administration area which will only be used by people I know. (And they all have modern browsers.)</p>