Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

XMLHttpRequest onprogress total is always 0 on Chrome

I am trying to show a progress bar before navigating from one page to another within the same website.

My function binds an updateProgress function to XMLHttpRequest onprogress event and it redirects user to a new page on (xhr.readyState == 4 && xhr.status == 200) It seems working fine except that Chrome shows "total" as zero which won't let the progress bar function properly. My code is below.

Thank you in advance...

$('.ajaxNavi').click(function (e) {
  e.preventDefault();
  var url = $(this).attr('href');
  var xhr = new XMLHttpRequest();
  xhr.onprogress = updateProgress;
  xhr.onreadystatechange = function () { 
    if (xhr.readyState == 4 && xhr.status == 200)
    // REDIRECT HERE
    }
  });
  xhr.open("GET", url, true);
  xhr.setRequestHeader("Content-Type", "text/html");
  xhr.send();
});

function updateProgress(e) {
  console.log(e.loaded + '    ' + e.total);
}
like image 651
B10 Avatar asked Jan 04 '15 16:01

B10


1 Answers

Two years late, but this question seems to have a lot of views and should probably be answered.

According to this question a gzipped response will always have lengthComputable set to false in Chrome. This makes a lot of sense because you may know how much more compressed data is coming down the pipe, but you can't have any idea how much that compressed data will expand to.

This solution seems like a good one to me.

like image 108
JosiahDaniels Avatar answered Oct 23 '22 04:10

JosiahDaniels