Reputation: 2119
I want to show the connection speed(Latency?) of the users of my website. I think it can be possible by measuring XMLHttpRequest object request and response times. The code is as follow.
var t;
function ajsend(){
var request = new XMLHttpRequest();
var url;
request.onreadystatechange = function(){
if( request.readyState == 4 && request.status == 200 ){
var u = new Date().valueOf();
var timeTaken = u - t;
var disp;
if( timeTaken < 100 )
disp = "Excellent! " + timeTaken + " milliseconds.";
else if( timeTaken < 500 )
disp = "Very Good! " + timeTaken + " milliseconds.";
else if( timeTaken < 1200 )
disp = "Normal! " + timeTaken + " milliseconds.";
else if( timeTaken < 2000 )
disp = "Poor! " + timeTaken + " milliseconds.";
else
disp = "Very Poor! " + timeTaken + " milliseconds.";
document.getElementById("disp").innerHTML = disp;
}
};
t = new Date().valueOf();
url = "noscript.php";
request.open("GET", url, true);
request.send();
}
It works! But the result is a bit different from the measurement of browser's Web Console. So, is it the best way from AJAX or any better way by AJAX? Thanks.
Upvotes: 4
Views: 1300
Reputation: 43253
If you want to compare the time on how long it takes for your server to start responding to the request, checking against readyState == 2
might work better.
In readyState 2, the request has received headers from the server, so it should be available somewhat sooner than readyState 4.
Also note that JavaScript is not accurate on the millisecond level so you may also get some differences because of that.
Upvotes: 1