Show Loading Graphic During Page Load

There are circumstances where it may be a better user experience if you display a loading graphic during page load. In a recent project I was tasked with displaying a page that included 12 posts, each of which had 3-5 high resolution images that needed to rotate when the user hovered over the featured image. That is between 36-60 high resolution images that needed to load … which can lead to long load times and annoyed users.

A nice way to keep users happy is to display a loading graphic during page load to give them a visual illustration of the page load. With a little HTML and jQuery we can accomplish this pretty easily.

Setup the Loading Graphic

First, we’ll want to ensure we have a div containing our loading graphic or content, that is completely separate from the div that holds the content that will be loading. For example:

<div class="loading-graphics">Loading...</div>
<div class="main-content" style="display:none;">Your content here...</div>

These divs need to be separate to allow us to show one while the page is loading, then hide it and show the other once the page has rendered. Notice the display:none set on the main-content container. This ensures that it is hidden (we’ll un-hide it with jQuery next). Note: You’ll want to do this in your stylesheet, not inline like it is here.

The jQuery Magic

Now we’ll write nice little jQuery script that will hide the loading div once the page loads, and then show the main content.

<script>
jQuery(window).load(function() {
  jQuery('.loading-graphics').fadeOut(1500);
  jQuery('.main-content').delay(1500).fadeIn(1500);
});
</script>

The first part of the code will ‘fadeOut’ the loading div once the page has loaded. It is set to fade over 1.5 seconds (1500ms). Next, the main-content container will ‘fadeIn’ over the same duration after a 1.5 second delay. This gives the first div a chance to completely disappear, prior to the main content fading in. Doing this prevents from the divs ‘jumping’ when they fade in/out. You can easily change out the 1500 with whatever time duration you’d like.

And the source code to go with the example can be found here.

Note: You will need to have jQuery enqueued for this to work properly.
Note 2: The example link also assumes you have enqueued Font Awesome.

Leave a Reply

Your email address will not be published. Required fields are marked *