Is it possible to preload page contents with ajax/jquery technique?

Ahmad Fouad picture Ahmad Fouad · Apr 8, 2009 · Viewed 28.5k times · Source

Is it possible to preload all page contents (like showing a loading bar / animated gif.. or loading text.. ) until the contents are fully loaded and then displayed to the user/visitor ? If this is possible, can you give me just directions or resources to follow to achieve this. Because I was able to find image preloaders easily, but I am seeking for a preloading technique that will preload all content on the page before being displayed.

Answer

sepehr picture sepehr · Apr 8, 2009

There's no need to use Ajax for this. Simply set the page's wrapper div display to none. Then change it to block when the document is loaded.

Your code might look like this, using vanilla javascript:

<script type="text/javascript">
    function preloader() {
        document.getElementById("preloader").style.display = "none";
        document.getElementById("container").style.display = "block";
    }

    window.onload = preloader;
</script>

<style>
div#wrapper {
    display: none;
}

div#preloader {             
    top: 0; right: 10px;
    position:absolute;
    z-index:1000;
    width: 132px; height: 38px;
    background: url(path/to/preloaderBg.png) no-repeat;
    cursor: wait;
    text-shadow: 0px 1px 0px #fefefe;  //webkit                 
}
</style>

<body>
    <div id="preloader">Loading... Please Wait.</div>
    <div id="wrapper">
        <!-- page contents goes here -->
    </div>
</body>

Update, in jQuery:

<script type="text/javascript">
    // Use $(window).load(fn) if you need to load "all" page content including images, frames, etc.
    $(document).ready(function(){ 
        $("#preloader").hide();
        $("#container").show();
    });
</script>

Related documents: Events/ready, Events/load, CSS/css & Core/$