jQuery whole HTML page load with spinner

user1317510 picture user1317510 · May 24, 2012 · Viewed 78.5k times · Source

I am trying to something simple -- make a jQuery script that will wait to show the entire page, including all DIVs, text, and images. While the page is loading, instead of showing parts of the page I would like to show a spinning GIF image, and when the entire page is loaded we can fade the contents of the page in the browser window.

There are plenty of scripts to load with an ajax request into a container DIV -- but this is different. This will show a spinning GIF while an HTML page is loading. Any help is appreciated

This type of script only works on ajax requests

$('#loadingDiv')
    .hide()  // hide it initially
    .ajaxStart(function() {
        $(this).show();
    })
    .ajaxStop(function() {
        $(this).hide();
    });

Answer

AvL picture AvL · May 24, 2012

$(document).ready(...) fires as soon the DOM is loaded. This is too soon. You should use $(window).on('load', ...):

JavaScript:

$(window).on('load', function(){
    $('#cover').fadeOut(1000);
})

CSS:

#cover {
    background: url("to/your/ajaxloader.gif") no-repeat scroll center center #FFF;
    position: absolute;
    height: 100%;
    width: 100%;
}

HTML:

<div id="cover"></div>
<!-- rest of the page... -->

look at this jsFiddle: http://jsfiddle.net/gK9wH/9/