Progress bars are really interesting. It keeps the user’s curiosity to monitor the completion of api request. Requests can be light or heavy (e.g downloading large file) depending on the application taking less or more time respectively. Long waiting time can not only ruin the user experience but confuse them regarding functionality of web application. That’s why we use progress bars to engage them.

In this article, I will give a seed code and quick walk through the same to integrate bootstrap progress bars for AJAX requests. The idea is simple, we have to monitor the on progress event and according to the percentage of data received modify the width of the progress bar. Read more here.

The JavaScript function to update the progress bars is given below :

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
function updateProgress() {
    var bar = $('#mybar');
    // Lets pick a sample url of google maps api. Use your URL
    var url = 'https://maps.googleapis.com/maps/api/streetviewsize=400x400&location=40.720032,-73.988354&fov=90&heading=235&pitch=10'
    var xhr = new XMLHttpRequest();
    xhr.open("GET", url, true);
    xhr.responseType = "document";

    xhr.addEventListener("load", function () {
        if (xhr.status === 200) {

        // Do something..
        alert('Reqeuest Completed !!');
        } else {
        alert('Error making the request');
        }
    }, false);

    var prev_percent = 0;
    xhr.addEventListener("progress", function(event) {
        if (event.lengthComputable) {

            // Update progress bars
            var percent = Math.round((event.loaded / event.total) * 100);
            if (percent != prev_percent) {
                prev_percent = percent;
                bar.css('width', percent+"%");
                bar.html(percent+"%");
            }
       }
   });
   xhr.send();
}

View on github

Above function uses lengthComputable, loaded and total attribute of progress event to calculate the percentage of event loaded. I tested this code for a simple URL where the request was very fast. You can try with different urls with greater response time and notice the change.