Javascript Loading Screen
This script uses both Javascript and CSS to display a loading screen that
disappears after the page has finished loading. You can use CSS to customize the
loading screen div as much as you want. It works in all browsers, including
Firefox and Internet Explorer.
Click here to view the loading screen demo (URL: loading-screen.html)
The Loading Div CSS
Place this code in the head tag:
You can customize this CSS however you want. Just make sure that in
loading-invisible it is set to display:none and in loading-visible it is set to
display:block. This CSS should be modified if you want the loading screen to be
full screen (URL: javascript-css-load-screen-full-screen.html), vertically
centered (URL: javascript-css-load-screen-center-screen.html), or positioned in
the top-right corner (URL: javascript-css-loading-screen-top-right-corner.html).
The Loading Screen HTML
Place this code right at the top of the body tag:
Your content (like a loading GIF)
Inside of the div, you can put anything you'd like, including any kind of
animated GIF.
The Loading JavaScript
Now here is the fun part! Put this code right after the loading div:
You are done!
JavaScript Walkthrough
Now that your loading screen is working, let's walk through the simple
JavaScript to see how it works.
document.getElementById("loading").className = "loading-visible";
This line changes the class of the loading div from loading-invisible to
loading-visible. So, why didn't we just make the div visible in the first place?
Because if the user does not have JavaScript enabled, JavaScript will never be
able to make the div invisible. Thus, the div should only become visible if our
script is actually running.
var hideDiv = function(){document.getElementById("loading").className =
"loading-invisible";};
This defines a function that will be used to hide the loading div by setting its
class to loading-invisible.
var oldLoad = window.onload;
This gets the current value of window.onload. This variable will contain a
function if you have already set an onload function somewhere else on your page.
var newLoad = oldLoad ? function(){hideDiv.call(this);oldLoad.call(this);} :
hideDiv;
window.onload = newLoad;
Here is how you should read these lines: if there was already an onload function
set, then the new onload should hide the loading div and then call the old
onload. Otherwise, it only needs to hide the loading div.
Code Explanation Overview
So, basically, here is what all this code does.
A hidden loading div is created with some content, like an animated GIF. Then,
JavaScript unhides the div. When the page has finished loading, JavaScript hides
the div again.
If you have any questions, please just contact me (URL: contact.html).