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 for this! I'd liek to add a little riff on the J-P's answer - I don't know if this will help anyone, but this way you don't have to create an array of images, and you can preload all your large images if you name your thumbs correctly. This is handy because I have someone who is writing all the pages in html, and it ensures one less step for them to do - eliminating the need to create the image array, and another step where things could get screwed up.
Basically, for each image on the page it grabs the src of each image, if it matches certain criteria (is a thumb, or home page image) it changes the name(a basic string replace in the image src), then loads the images.
In my case the page was full of thumb images all named something like image_th.jpg, and all the corresponding large images are named image_lg.jpg. The thumb to large just replaces the _th.jpg with _lg.jpg and then preloads all the large images.
Hope this helps someone.
5 lines in coffeescript
JP, After checking your solution, I was still having issues in Firefox where it wouldn't preload the images before moving along with loading the page. I discovered this by putting some
sleep(5)
in my server side script. I implemented the following solution based off yours which seems to solve this.Basically I added a callback to your jQuery preload plugin, so that it gets called after all the images are properly loaded.
Out of interest, in my context, I'm using this as follows:
Hopefully this helps someone who comes to this page from Google (as I did) looking for a solution to preloading images on Ajax calls.
Use JavaScript Image object.
This function allows you to trigger a callback upon loading all pictures. However, note that it will never trigger a callback if at least one resource is not loaded. This can be easily fixed by implementing
onerror
callback and incrementingloaded
value or handling the error.This one line jQuery code creates (and loads) a DOM element img without showing it: