show progressbar while loading pages using jquery ajax in single page website

Allow me to refer you to this page , it desribes how you can add a progress event listener to the xhr object (which only works in these browsers, in older browsers you simply have rely on the same base you’re currently using) in jquery.

For reference I have copied the relevant code below (you would only be interested in the ‘Download progress’ part probably):

$.ajax({
  xhr: function()
  {
    var xhr = new window.XMLHttpRequest();
    //Upload progress
    xhr.upload.addEventListener("progress", function(evt){
      if (evt.lengthComputable) {
        var percentComplete = evt.loaded / evt.total;
        //Do something with upload progress
        console.log(percentComplete);
      }
    }, false);
    //Download progress
    xhr.addEventListener("progress", function(evt){
      if (evt.lengthComputable) {
        var percentComplete = evt.loaded / evt.total;
        //Do something with download progress
        console.log(percentComplete);
      }
    }, false);
    return xhr;
  },
  type: 'POST',
  url: "https://stackoverflow.com/",
  data: {},
  success: function(data){
    //Do something success-ish
  }
});

Do allow me to say though that this is a lot of overkill for a single page website and only really becomes useful for large files. Additionally images and similar media aren’t handled in this way and you would need to monitor the loading of images (or do it yourself through ajax) to make such a system perfect.

Here is a JSFiddle showing this in action: http://jsfiddle.net/vg389mnv/1/

Leave a Comment