Thursday, December 1, 2011

preload your images


Sometimes when building a dynamic site, you might want to load some images after the page has loaded but before the images are shown so that when they do show the appear instantly.

I forget where I found this paradigm, probably somewhere on stackoverflow, but it seemed to work a treat:
function preload(sources, prefix)
{
  var images = [];
  for (var i = 0; i < sources.length; ++i) {
    images[i] = new Image();
var src = sources[i];
if(prefix != undefined){
 src = prefix + src;
}
    images[i].src = src;
  }
}

(Ha, I can tell it's not all my code, I never do "++i".) Sources is an array of image names, prefix is an optional parameter that might contain the URL for the directory where the images are located, so you don't have to include the path on each image name. Then when you actually show the image it should be ready to go, instantly.

No comments:

Post a Comment