How to show Page Loading div until the page has finished loading?

Original Answer

I’ve needed this and after some research I came up with this (jQuery needed):

First, right after the <body> tag add this:

<div id="loading">
  <img id="loading-image" src="path/to/ajax-loader.gif" alt="Loading..." />
</div>

Then add the style class for the div and image to your CSS:

#loading {
  position: fixed;
  display: block;
  width: 100%;
  height: 100%;
  top: 0;
  left: 0;
  text-align: center;
  opacity: 0.7;
  background-color: #fff;
  z-index: 99;
}

#loading-image {
  position: absolute;
  top: 100px;
  left: 240px;
  z-index: 100;
}

Then, add this javascript to your page (preferably at the end of your page, before your closing </body> tag, of course):

<script>
  $(window).load(function() {
    $('#loading').hide();
  });
</script>

Finally, adjust the position of the loading image and the background-color of the loading div with the style class.

This is it, should work just fine. But of course you should have an ajax-loader.gif somewhere or use base64 url for image’s src value. Freebies here. (Right-click > Save Image As…)

Update

For jQuery 3.0 and above you can use:

<script>
  $(window).on('load', function () {
    $('#loading').hide();
  }) 
</script>

Update

The original answer is from jQuery and before flexbox era. You can use many view management libraries / frameworks now like Angular, React and Vue.js. And for CSS you have flexbox option. Below is CSS alternative:

#loading {
  position: fixed;
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100%;
  height: 100%;
  top: 0;
  left: 0;
  opacity: 0.7;
  background-color: #fff;
  z-index: 99;
}

#loading-image {
  z-index: 100;
}

Leave a Comment