Show loading icon while actual image is loading using jQuery

Showing loading for ajax content is pretty common thing but suppose there is a quite big image (in size) on your page and it is taking lots of time to load. Would it not be nice to show loading icon for the same? Well, it creates a nice user experience. The user will come to know that something is loading. So in this post, I will show you how to show loading icon while actual image is loading using jQuery.

The idea is to call a function, which will show the loading icon unless the actual images is fully loaded. You can use .load() function with images to achieve this. So lets first you define a small loading image.

<img src="images/loading.gif" id="imgLoader" />

Here is your actual images.

<img src="images/background.jpg" id="imgMain" />

Below jQuery code, first shows the loading images and as soon as the main images is completely loaded then it hides the loading image. Simple.

$(document).ready(function(){
    $('#imgLoader').show();
    $('#imgMain').load(function(){
      $('imgLoader').hide();
  });
});

The above code works very well for single image. But lets say there are multiple images and you want to show loading icon for each image. And the important thing is we can't have multiple loading images as per the number of images. The ideal solution is to use single loading image for all the images.

So the solution is to first find total number of images on the page. And also have a counter which gets incremented when every image is loaded. And hide the loading image when all the images are loaded.

$(document).ready(function(){
   $('#imgLoader').show();
   var totalImages = $(".imgClass").length;
   var iLoaded = 0;
   $(".imgClass").each(function () 
   {
     $(this).bind("load", function()
     {
       iLoaded++;
       if(iLoaded == totalImages)
       {
          $('#imgLoader').hide();
       }
       $(this).attr('src', $(this).attr("src"));
    });
  });
});

Hope you find it useful.

Feel free to contact me for any help related to jQuery, I will gladly help you.



Responsive Menu
Add more content here...