Creating a site loader has always been a required task with jQuery. However, many times we've noticed strange behaviors in older versions of Internet Explorer so that we often neglect this feature because we're slightly aware of the consequences. But the web is expanding and new concepts of web applications are entering the scene. We can't afford to be afraid of Internet Explorer, because dinosaurs like it are dead, so let the past be past. We can't always live in fear. Said that, let's take a look at how we can accomplish this with jQuery.
We basically need two things: an overlay element and a page spinner. A page spinner is an animated GIF that shows an action in progress. Let's put these elements just before our main site container:
<div id="overlay"> <img src="page-loader.gif" alt="" /> </div> <div id="site"> <!--site contents here--> </div>
Our GIF must have an empty alt
attribute so that it won't generate any confusion in screen readers. Now we need to define some specific styles. First, we need a full width and height for the page:
html, body { width: 100%; height: 100%; margin: 0; padding: 0; min-height: 100%; }
We'll use negative absolute positioning to hide the site contents. To accomplish this, we must first set a context for positioning:
body { margin: 0; padding: 0; background: #fff; color: #333; font: 100% "Trebuchet MS", Trebuchet, sans-serif; position: relative; } #site { width: 100%; position: absolute; top: -1000em; margin: 0; }
So our site container is hidden. We can define some styles for our overlay element:
#overlay { background: #c60; height: 100%; width: 100%; position: absolute; top: 0; left: 0; } #overlay img { display: block; position: absolute; top: 50%; left: 50%; width: 66px; height: 66px; margin: -33px 0 0 -33px; }
This element will have full dimensions and the page spinner will be horizontally and vertically centered within it. Now you may ask: why don't create such element with jQuery? Simply put, if you create the overlay with jQuery, the undesired effect of a blank page will appear and we don't want that.
Finally, we create a timer that waits 3 seconds, then it removes the overlay element and shows the site contents:
$(document).ready(function() { var seconds = 0; var interval = window.setTimeout(function() { seconds += 1; if(seconds == 3) { window.clearTimeout(interval); $('#overlay').remove(); $('#site').animate({ top: 0 }); } window.setTimeout(arguments.callee, 1000); }, 1000); });
You can see the demo below.