我想显示我网站用户的连接速度(延迟?)。我认为可以通过测量 XMLHttpRequest 对象的请求和响应时间来实现。代码如下。
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();
}
有用!但结果与浏览器的 Web Console 的测量结果有点不同。那么,它是 AJAX 的最佳方式还是 AJAX 的任何更好的方式?谢谢。