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.

jQuery(window).load(function() {

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.

Here is a working example.

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.

Get New Posts in Your Inbox

This field is for validation purposes and should be left unchanged.

About Matt Whiteley

Matt has been building bespoke WordPress websites for over 10 years specializing in the Genesis Framework. He integrates Advanced Custom Fields heavily in all builds, especially with the new Gutenberg Block Editor, allowing clients to easily modify all aspects of the their website with ease.

He works with a wide variety of small businesses and agencies across the country providing development services as well as hosting and maintenance. When he isn't coding he enjoys spending time with his wife and two children, golfing and playing poker.

Reader Interactions

Leave a Reply

Your email address will not be published.