views:

5779

answers:

3

I'm looking for a quick and easy way to preload images with JavaScript. I'm using jQuery if that's important.

I saw this here (http://nettuts.com...):

function complexLoad(config, fileNames) {
  for (var x = 0; x < fileNames.length; x++) {
    $("<img>").attr({
      id: fileNames[x],
      src: config.imgDir + fileNames[x] + config.imgFormat,
      title: "The " + fileNames[x] + " nebula"
    }).appendTo("#" + config.imgContainer).css({ display: "none" });
  }
};

But, it looks a bit over-the-top for what I want!

I know there are jQuery plugins out there that do this but they all seem a bit big (in size); I just need a quick, easy and short way of preloading images!

Thanks! :-D

+33  A: 

Quick and easy:

function preload(arrayOfImages) {
    $(arrayOfImages).each(function(){
        $('<img/>')[0].src = this;
        // Alternatively you could use:
        // (new Image()).src = this;
    });
}

// Usage:

preload([
    'img/imageName.jpg',
    'img/anotherOne.jpg',
    'img/blahblahblah.jpg'
]);

Or, if you want a jQuery plugin:

$.fn.preload = function() {
    this.each(function(){
        $('<img/>')[0].src = this;
    });
}

// Usage:

$(['img1.jpg','img2.jpg','img3.jpg']).preload();
J-P
Whoa, that was quick, THANKS!!! Looks really good!
Howcome this code doesn't work for me? Does it work for others?
Amit
Doesn't the image element need to be inserted into the DOM to ensure the browser caches it?
JoshNaro
+1  A: 

truth be told, that looks like a pretty concise way of handling the problem? What exactly is it about this code that is over the top? at the end of the day, does it meet your requirement of preloading imgs?

Joel Martinez
Just reading some of the comments on that nettuts article it seems it appends new images to the DOM in order to preload them, that's not necessary!
Actually it is. IE discards image objects (that aren't written to the DOM) within a very short space of time. The only way to guarantee that an image will be cached is to add it to the DOM.
James
A: 

thenkyou it is great

elbek