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!
this jquery imageLoader plugin is just 1.39kb
usage:
there are also other options like whether you want to load the images synchronously or asychronously and a complete event for each individual image.
This works for me even in IE9:
.attr('src',value)
not.attr('src',this)
just to point it out :)
I have a small plugin that handles this.
It's called waitForImages and it can handle
img
elements or any element with a reference to an image in the CSS, e.g.div { background: url(img.png) }
.If you simply wanted to load all images, including ones referenced in the CSS, here is how you would do it :)
I wanted to do this with a Google Maps API custom overlay. Their sample code simply uses JS to insert IMG elements and the image placeholder box is displayed until the image is loaded. I found an answer here that worked for me : https://stackoverflow.com/a/10863680/2095698 .
This preloads an image as suggested before, and then uses the handler to append the img object after the img URL is loaded. jQuery's documentation warns that cached images don't work well with this eventing/handler code, but it's working for me in FireFox and Chrome, and I don't have to worry about IE.
Here's a tweaked version of the first response that actually loads the images into DOM and hides it by default.