测量ajax接收时间

ixt*_*xth 1 javascript ajax jquery

我正在尝试测量下载/上传速度并同时制作大量的ajax请求.由于浏览器连接限制,其中一些被阻止,所以我无法通过这样做来建立真正的下载时间:

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

所以,我用这种方式使用原始xhr:

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();
Run Code Online (Sandbox Code Playgroud)

有没有办法使用jQuery做同样的事情?

UPDATE

我需要start在ajax请求之前初始化,但是在requestState更改为2或3之后(实际下载/上传).

更新#2

jQuery bugtracker中存在相关问题:http://bugs.jquery.com/ticket/9883

Geo*_*ith 6

$.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();
      }
   }
});
Run Code Online (Sandbox Code Playgroud)

使用jQuery.ajax()方法,complete回调会触发successerror(在这些回调之后...如果你想使用那些回调,则使用单独的回调).

更新(请参阅您的评论):使用此处的代码:https://gist.github.com/chrishow/3023092利用该.ajaxPrefilter()方法我们可以为方法添加一个onreadystatechange选项.ajax().