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:
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 < 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();
}
}
}
But that did not made any difference.
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:
$file= base64_encode( file_get_contents ( 'img/0.png') );
echo 'images["img/0.png"] = "data:image/png;base64,'.$file.'";';
That way I could also “hardcode” the images directly into my HTML, right?
I thought that in JavaScript I could do this:
$(".selector").attr("src", images['filename']);
Is this a good solution? Or is there a “proper”/better way?
Thanks!
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.)
The
dataURI scheme isn’t supported by IE (or if it is, it’s a very recent addition).I’d fix the fact that the browser isn’t always taking the image from the cache, since it should be. Double check you aren’t using a variant of the URI for some calls, and then check that the headers sent are appropriate and giving a max-age of at least an hour, if not more.
It also never hurts with images for this sort of use to use pngslim or similar to shave off every byte of what’ll be sent.