Preload images with jQuery

preload images using jquery

Using jQuery it is very easy to preload images with jQuery on a web page. All you need to do is form a JSON object with image paths as data and pass that JSON object to preload function then the function will iterate the JSON and assign each path as a source to an img tag.

By doing this we can improve the page loading performance but I recommend you to optimize your images before using them in the application which will improve the more better performance of your website.

To increase your website performance by doing Gzip compression please read my article on How to speed up your website with gzip compression.

Below is the preload jquery function:


function preload(arrayOfImages) {
$(arrayOfImages).each(function(){
$('<img/>')[0].src = this;
// Alternatively you could use:
// (new Image()).src = this;
});
}

// Usage:

preload([
'img/imageName.jpg',
'img/anotherOne.jpg',
'img/blahblahblah.jpg'
]);

Or, if you want a jQuery plugin to preload images:


$.fn.preload = function() {
this.each(function(){
$('<img/>')[0].src = this;
});
}

// Usage:

$(['img1.jpg','img2.jpg','img3.jpg']).preload();

You may also like...