ixth
ixth

Reputation: 78

Measure ajax receive time

I'm trying to measure download/upload speed and make a lot of simultaneous ajax requests. Some of them get blocked due to browser connections limit, so I can't establish real download time by doing some kind of this:

var start = new Date;
$.get('/data').done(function () {
    console.log(new Date - start);
});

So, I'm using raw xhr this way:

var open, start, end;
var req = new XMLHttpRequest();
req.open('GET', '/data', true);
req.onreadystatechange = function () {
    switch (this.readyState) {
        case 2:
        case 3:
            if (!start) { start = new Date(); }
            break;
        case 4:
            if (!end) { end = new Date(); }
            console.log('%d: pending = %d, download = %d, total = %d', i, start - open, end - start, end - open);
            break;
    }
};
if (!open) { open = new Date(); }
req.send();

Is there any way to do the same using jQuery?

UPDATE

I need to initialize start not before ajax request, but after requestState changed to 2 or 3 (actually downloading/uploading).

UPDATE #2

There's related issue in jQuery bugtracker: http://bugs.jquery.com/ticket/9883

Upvotes: 1

Views: 926

Answers (1)

George Reith
George Reith

Reputation: 13476

$.ajaxPrefilter(function( options, originalOptions, jqXHR ) {
    if ( options.onreadystatechange ) {
        var xhrFactory = options.xhr;
        options.xhr = function() {
            var xhr = xhrFactory.apply( this, arguments );
            function handler() {
                options.onreadystatechange( xhr, jqXHR );
            }
            if ( xhr.addEventListener ) {
                xhr.addEventListener( "readystatechange", handler, false );
            } else {
                setTimeout( function() {
                    var internal = xhr.onreadystatechange;
                    if ( internal ) {
                        xhr.onreadystatechange = function() {
                            handler();
                            internal.apply( this, arguments ); 
                        };
                    }
                }, 0 );
            }
            return xhr;
        };
    }
});    

var start = null;
var xhr = $.ajax({
   url: "/data",
   complete: function() {
      var end = new Date().getTime();
      var requestTime = end - start;
      console.log(requestTime);
   }
   onreadystatechange: function(xhr) {
      if(xhr.readyState == 3 && start == null) {
         start = new Date().getTime();
      }
   }
});

Using the jQuery.ajax() method the complete callback fires on success or error (After those callbacks... use individual callbacks if you want to make use of those).

Update (See your comment): Using the code sourced from here: https://gist.github.com/chrishow/3023092 utilising the .ajaxPrefilter() method we can add an onreadystatechange option to the .ajax() method.

Upvotes: 6

Related Questions