Image Preloader

With Ajax being all the rage, pre­load­ing images has become some­what import­ant. The prob­lem is, load­ing them with all the other page com­pon­ents adds to the load time and it may not even be used. Enter preloadImage — a func­tion set to stop all that. It’s very simple but can be used to power­ful means:

var preloadImage = function(url, callback) {
	var image = new Image();
	image.src = url;
	image.onload = image.onabort = image.onerror = callback;
	return image;
};

Just spe­cify the URL (url) and the call­back func­tion (callback) as so:

var callback = function(e) {
	alert(e.type);
};

var image = preloadImage('http://www.sidroberts.co.uk/image.gif', callback);

On the load event, the abort event or the error event, the call­back func­tion will be executed. You can dis­tin­guish these with the type prop­erty which is "load", "abort" and "error" respectively.

Now any image that points to that URL will load almost instantly.

Comments

No responses have been made so far. Add your comments.

    What do you think? Leave a comment...