How to display a loading screen while site content loads

user27171 picture user27171 · Oct 28, 2008 · Viewed 162.2k times · Source

I'm working on a site which contains a whole bunch of mp3s and images, and I'd like to display a loading gif while all the content loads.

I have no idea how to achieve this, but I do have the animated gif I want to use.

Any suggestions?

Answer

mmattax picture mmattax · Oct 28, 2008

Typically sites that do this by loading content via ajax and listening to the readystatechanged event to update the DOM with a loading GIF or the content.

How are you currently loading your content?

The code would be similar to this:

function load(url) {
    // display loading image here...
    document.getElementById('loadingImg').visible = true;
    // request your data...
    var req = new XMLHttpRequest();
    req.open("POST", url, true);

    req.onreadystatechange = function () {
        if (req.readyState == 4 && req.status == 200) {
            // content is loaded...hide the gif and display the content...
            if (req.responseText) {
                document.getElementById('content').innerHTML = req.responseText;
                document.getElementById('loadingImg').visible = false;
            }
        }
    };
    request.send(vars);
}

There are plenty of 3rd party javascript libraries that may make your life easier, but the above is really all you need.