Home > Javascript, Web Design > Preload images with jQuery

Preload images with jQuery

Sometimes you might want to preload some images used in your site to improve user experience. In photo galleries or other image-heavy sites preloading images help visitor enjoy faster loading times.


jQuery can help us with a few lines of code to achieve that:

//Function that preloads a defined list of images (arguments for the function).
 jQuery.preloadImages = function(){
  //Loop through the images
  for(var i = 0; i<arguments.length; i++){
    jQuery("<img>").attr("src", arguments[i]);
  }
}

// Call the function:
$.preloadImages("images/1.png", "images/2.png", "images/3.png", "images/4.jpg");
Categories: Javascript, Web Design Tags: