How to get a progress bar in jQuery.get ()

advertisements

is it possible to have a progress bar measuring the jQuery.get() progress?


This is not given out-of-the-box in the current version of jQuery, but still possible with little effort.

You should listen to the progress event of the XMLHttpRequest which jQuery gives you access to. An example from Dave Bond's blog:

$.ajax(
{
  type: 'POST', // 'POST' here so that _upload_ progress _also_ makes sense;
                // Change to 'GET' if you need.
  url: "/", data: {},
  beforeSend: function(XMLHttpRequest)
  {
    //Upload progress
    XMLHttpRequest.upload.addEventListener("progress", function(evt){
      if (evt.lengthComputable) {
        var percentComplete = evt.loaded / evt.total;
        //Do something with upload progress
      }
    }, false); 

    //Download progress
    XMLHttpRequest.addEventListener("progress", function(evt){
      if (evt.lengthComputable) {
        var percentComplete = evt.loaded / evt.total;
        //Do something with download progress
      }
    }, false);
  },

  success: function(data){
    // successful completion handler
  }
});

Here the link to the docs on XMLHttpRequest's progress event.

You may also want to take a look a the jquery.ajax-progress plugin to avoid doing it yourself.


Notes:

  • Some older browsers may not support the progress event.

  • To calculate download progress, you must know the size of the resource to be downloaded, i.e. the server must send the Content-length HTTP header. If size is not known, then it's not possible to calculate the progress. This is what the lengthComputable property of the progress event is for.