Show loading image while Page is loading using jQuery

Web pages takes time to load and sometimes when page is heavy (full of images) then it takes more time to load. Would it not be nice to show loading images or message while your page is loading. It creates responsive webpage and gives nice user experience. The user will come to know that something is loading.

Earlier I had posted about Execute jQuery code only after Web Page is loaded completely and Show loading icon while actual image is loading using jQuery. In this post, I will show you how to show loading icon/image while page is loading using jQuery.

How to do it?

First create a div element and assign an ID to it. I have assigned ID as "dvLoading". This div element will be used to show the loading icon.

<div id="dvLoading"></div>

Now create a style which will be applied to the div element. Basically, this CSS style will set the div position in the middle of the page and also assign width and height. And the background of the div will be an loading gif image.

#dvLoading
{
   background:#000 url(images/loader.gif) no-repeat center center;
   height: 100px;
   width: 100px;
   position: fixed;
   z-index: 1000;
   left: 50%;
   top: 50%;
   margin: -25px 0 0 -25px;
}

Now, comes the jQuery part. The div element will be always visible but we need to hide it as soon as our page is loaded completely. In this case, we can't use $(document).ready() to show the loading div. Read here why? Therefore, we need to use window.load event to hide the loading div element. Remember to put this code before closing head tag.

<script>
$(window).load(function(){
  $('#dvLoading').fadeOut(2000);
});
</script>

That's it!!!!!

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



Responsive Menu
Add more content here...