jQuery

jQuery Preload Images Using Custom Function Example

Have you ever wanted to speed up the process of preloading images using jQuery? Here is an excellent way to use jQuery to preload images.

How to Preload Images using jQuery

The following is a sample code. Simply replace the values of “my_images” array with the proper path of your images are you are done!

Example 1: Use jQuery to Preload Images

<script type="text/javascript" language="javascript" >
$(document).ready(function(){

//Function to preload images
function preload_images(images_array)
{
$(images_array).each(function () {
$('<img />').attr('src',this).appendTo('body').css('display','none');
});
}

//Define an array of images
var my_images = ['images/1.jpg',  'images/2.jpg', 'images/3.jpg'];

//Call the function on the array of images
preload_images(my_images);
});
</script>
That’s it!

Do you know of any other ways to preload images using jQuery? Feel free to suggest by commenting below.

4 Comments on jQuery Preload Images Using Custom Function Example

  1. 1

    This is fantastic. I have really never had the need to pre-load, but I am now designing a site that requires it. This is good info!

  2. 3

    If you prefer to avoid using JavaScript for the image preloads there are a couple CSS methods:

    http://www.scriptalicious.com/blog/2011/08/using-css-to-preload-images-without-javascript/

    Another way is to use the background-image property and relocate the image using absolute positioning.

Leave a Reply to Robert Cancel reply

*

*