Web development blog for Html, CSS, javascript, JQuery developers. At Kodecrash you will find best solution for complex problems.

Preload images using jQuery

Posted in JQuery, Jquery interview questions

In your web applications, if you are using lot of images also if there are some hover, slider, animation effects then those are not working properly when you load page first time. The reason is images take some time to load. To overcome this use image preloading. When images are preloaded in the browser, user can visit entire application seamlessly with faster loading experience. You can preload images using javascript, css. See below example.

var imagesArray=["abc.png","slider_1.png","slider_2.png","slider_3.png"];

Create an array of images which you want to preload. Iterate through each image and create image object and assign imagePath to image object. In this case, you are just making a request for image to server for each newly created image object. This image object is of no use, we are using this just for pre-loading purpose.

var imagePath="/images/";
var totalImages= imagesArray.length;

$.each(imagesArray, function(index, value){
    var img= new Image();
    console.log("Image "+ value +"  is loaded");
    var percentImagesLoaded= ((index+1)/totalImages)*100;
    console.log("Loading: "+ percentImagesLoaded);

    * code to hide loading image
   // if(percentImagesLoaded==100){
       // hide loading image
   // }

You can show a image preloader while images are loading. Create a dummy div which will show loading image and after all images are loading then hide this dummy div.