Simple Progress (Load) Bar with jQuery

Let's say you need to load some info into a page, but the info requires some time to process. You don't want to have the user staring at a blank screen during the processing, so first load the page with a busy (progress) bar image and then replace the image with the actual data when ready.

Assume you have this HTML page :


<html>
<head>
  <script type="text/javascript" src="/js/jquery.js"></script>
  <script type="text/javascript">
    $(document).ready(function() {
        $('#one').load('/one.php');
        $('#two').load('/two.php');
    });
  </script>
</head>

<body>
  <div id="one">Loading one...<img src="/img/download.gif"></div>
  <div id="two">Loading two...<img src="/img/download.gif"></div>
</body>
</html>

Assume one.php looks like this :


<?php
sleep(rand(2,10));
print "one from php";

You can grab a nice busy/progress bar image from here : http://www.ajaxload.info

The above jQuery is pretty simple. Initially, the page loads with with the two progress bar images spinning. After the document loads, jQuery starts up, and the content in divs one and two are replaced by the simple content from one.php and two.php. The PHP scripts just sleep a random amount to replicate processing.

After the PHP scripts are done, the content is returned (via jQuery's load function) to the page, replacing the original progress bar images.

This worked for me under Firefox 3.5, IE 6.x, and Chrome 4.x.

Categories: 

There are 2 Comments

Thanks for this super simple tutorial - this is exactly what I needed for something I was working on; didn't find the connection between page load and progress bar anywhere until I landed here!