AJAX(Asynchronous JavaScript and XML)请求持续时间是指从发起请求到接收到完整响应所经历的时间。这个指标对于性能分析和优化至关重要。
var xhr = new XMLHttpRequest();
var startTime, endTime;
xhr.onreadystatechange = function() {
if (xhr.readyState === 1) { // OPENED
startTime = new Date().getTime();
} else if (xhr.readyState === 4) { // DONE
endTime = new Date().getTime();
var duration = endTime - startTime;
console.log('请求持续时间: ' + duration + 'ms');
}
};
xhr.open('GET', 'https://api.example.com/data', true);
xhr.send();
const startTime = performance.now();
fetch('https://api.example.com/data')
.then(response => {
const endTime = performance.now();
const duration = endTime - startTime;
console.log(`请求持续时间: ${duration}ms`);
return response.json();
})
.catch(error => console.error('Error:', error));
// 发起请求前
performance.mark('ajaxStart');
fetch('https://api.example.com/data')
.then(response => {
performance.mark('ajaxEnd');
performance.measure('ajaxDuration', 'ajaxStart', 'ajaxEnd');
const measures = performance.getEntriesByName('ajaxDuration');
console.log(`请求持续时间: ${measures[0].duration}ms`);
// 清理性能条目
performance.clearMarks();
performance.clearMeasures();
return response.json();
});
原因:使用Date.now()而非performance.now(),前者精度只有毫秒级 解决:改用performance.now(),它提供微秒级精度
原因:跨域请求可能缺少某些时间阶段 解决:确保服务器设置了正确的CORS头部
原因:网络状况不稳定或服务器负载变化 解决:多次测量取平均值,或在受控环境中测试
通过准确测量AJAX请求持续时间,开发者可以更好地理解和优化应用性能。
没有搜到相关的文章