javascript - Measure ajax receive time -
i'm trying measure download/upload speed , make lot of simultaneous ajax requests. of them blocked due browser connections limit, can't establish real download time doing kind of this:
var start = new date; $.get('/data').done(function () { console.log(new date - start); });
so, i'm using raw xhr 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 way same using jquery?
update
i need initialize start
not before ajax request, after requeststate
changed 2 or 3 (actually downloading/uploading).
update #2
there's related issue in jquery bugtracker: http://bugs.jquery.com/ticket/9883
$.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 jquery.ajax() method complete
callback fires on success
or error
(after callbacks... use individual callbacks if want make use of those).
update (see comment): using code sourced here: https://gist.github.com/chrishow/3023092 utilising .ajaxprefilter()
method can add onreadystatechange
option .ajax()
method.
Comments
Post a Comment