jQuery: page loading delay

In this post I'm going to show you how to add a delay when a page is loading in order to insert an AJAX spinner using jQuery. To accomplish this task, we need to use both the load and ready events on window and document, respectively. After three seconds, the overlay inserted during the loading process will be removed and the content of the page will be shown in full. Let's get started with a couple of CSS rules:

html {
  margin: 0;
  padding: 0;
  width: 100%;
  height: 100%;
  min-height: 100%;

body {
 margin: 0 auto;
 width: 50%;
 line-height: 1.4;
 padding: 2em 0;
 background: #fff;
 color: #333;

#overlay {
 width: 100%;
 height: 100%;
 position: absolute;
 top: 0;
 left: 0;
 background: gray;

#overlay img {
 display: block;
 width: 32px;
 height: 32px;
 position: absolute;
 top: 50%;
 left: 50%;
 margin: -26px 0 0 -26px;
 padding: 10px;
 background: #fff;
 -moz-border-radius: 6px;
 border-radius: 6px;

The overlay will be inserted just before the body element in order to cover all the contents of our document. Instead, the delay will be created by wrapping the ready event execution within a setTimeout() function:

$(window).load(function() {

  $('<div id="overlay"><img src="loading.gif" /></div>')
  .css('opacity', '0.5')
  window.setTimeout(function() {
    $(document).ready(function() {
    });}, 3000);


You can see a demo below.


Live demo

This entry was posted in by Gabriele Romanato. Bookmark the permalink.

Leave a Reply

Note: Only a member of this blog may post a comment.