Hide a webpage until it has fully loaded
I decided to write this post after someone recently asked on a forum how they could hide a webpage until it had fully loaded then display it. There are tutorials out there that will hide the page using css then use a JavaScript onload event to show the page when it has loaded. The problem with that is if the user has JavaScript disabled then they will never see your page. We can avoid this problem by making use of an event provided by the Prototype JavaScript framework as is explained in the following steps.
Step 1 – Set up Prototype
To start with you need to download the Prototype JavaScript framework from http://www.prototypejs.org/. You then need to include this in your page using a script tag in the head section of the document e.g. <script type=”text/javascript” src=”prototype.js”></script>.
Step 2 - Implement dom:loaded event listener to hide the page
The Prototype JavaScript framework provides a function called observe and an event called dom:loaded that fires immediately after the html is loaded and before any elements have loaded. We can use this event to apply a mask over the page that will hide the page while everything is loading. First we create an empty div element in the <body> with an id called ‘mask’ that we can style with some css to hide the page.
document.observe('dom:loaded', function () {
//create a new div element
var maskElement = document.createElement(’div’);
//create an id attribute
var idAttr = document.createAttribute(”id”);
//set the value of id attribute to ‘mask’
idAttr.nodeValue = “mask”;
//add the id attribute to the div element
maskElement.setAttributeNode(idAttr);
//get the body element
var body = document.getElementsByTagName(’body’);
//add the new div element to the body
body[0].appendChild(maskElement);
//get the mask div element
var mask = $(’mask’);
//style the mask so that it hides the whole page
mask.style.backgroundColor = ‘#fff’;
mask.style.position = ‘absolute’;
mask.style.top = ‘0px’;
mask.style.left = ‘0px’;
mask.style.width = ‘100%’;
mask.style.height = ‘100%’;
});
Step 3 - Implement onload event listener to show the page
No that the whole page has been hidden we need to show it again once the page has finished loading. The window.onload event listener can be used for this as it doesn’t fire until all elements on the page have fully loaded.
window.onload = function() {
//get the mask div element
var mask = $(’mask’);
//style the mask so that it is no longer displayed
mask.style.display = ‘none’;
}
There are limited uses for this technique and I would not recommend using it on a public website as you are likely to confuse your users by breaking convention. You may wish to add an animated loading gif so that the user knows that something is going on in the background and they should wait. This technique will not work on websites that use Flash.