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!
I would use an Manifest file to tell (modern) web browsers to also load all relevant images and cache them. Use Grunt and grunt-manifest to do this automatically and never worry again about preload scripts, cache invalidators, CDN etc.
https://github.com/gunta/grunt-manifest
The usage is quite simple:
http://jsfiddle.net/yckart/ACbTK/
I use the following code:
Quick and easy:
Or, if you want a jQuery plugin:
A quick, plugin-free way to preload images in jQuery and get a callback function is to create multiple
img
tags at once and count the responses, e.g.Note that if you want to support IE7, you'll need to use this slightly less pretty version (Which also works in other browsers):
you can load images in your html somewhere using css
display:none;
rule, then show them when you want with js or jquerydon't use js or jquery functions to preload is just a css rule Vs many lines of js to be executed
example: Html
Css:
jQuery:
Preloading images by jquery/javascript is not good cause images takes few milliseconds to load in page + you have milliseconds for the script to be parsed and executed, expecially then if they are big images, so hiding them in hml is better also for performance, cause image is really preloaded without beeing visible at all, until you show that!