May
2010

The easiest way to preload images with jQuery

I don’t use image preloading very often – in many cases it can be avoided by using sprites. Sometimes however it’s difficult to avoid it when injecting new image content that hasn’t been used before. To avoid loading delays it makes sense to preload it.

I was surprised to see how many websites are suggesting the use of long scripts and jQuery plugins to achieve what can be done with as little as one line of code.

For single images

var image = $('<img />').attr('src', '/path/to/image.png');

For multiple images

var images = [
	'/path/to/image1.png',
	'/path/to/image2.png'
];

$(images).each(function() {
	var image = $('<img />').attr('src', this);
});

Leave a comment

*

You may use these HTML tags:
<a> <b> <blockquote> <cite> <code> <em> <i> <strike> <strong>