// 获取页面加载时间
const loadTime = window.performance.timing.loadEventEnd - window.performance.timing.navigationStart;
console.log('页面加载时间:', loadTime);
// 获取资源加载时间
const resources = window.performance.getEntriesByType('resource');
resources.forEach(resource => {
console.log('资源URL:', resource.name);
console.log('资源加载时间:', resource.duration);
});
在 JavaScript 中,可以使用 window 对象的 fetch 和 XMLHttpRequest 事件来监控页面上的网络请求。以下是监控这些请求的示例代码:
// 监控fetch请求
window.addEventListener('fetch', event => {
const { request } = event;
console.log('Fetch request made:', request.url);
});
// 监控XMLHttpRequest请求
window.addEventListener('xhr', event => {
const { xhr } = event;
console.log('XHR request made:', xhr.responseURL);
});
这些监控方法只在支持的现代浏览器中有效,并且需要在浏览器的安全上下文中使用,例如在 HTTPS 协议下。此外,这些监控方法需要浏览器的特定权限,通常只有在开发者模式下或者某些扩展程序中才能使用。
对于旧版浏览器或不支持的浏览器,可以使用代理的方式来监控网络请求,例如使用 window.XMLHttpRequest.prototype.open 方法的代理来监控
(function() {
const originalOpen = window.XMLHttpRequest.prototype.open;
window.XMLHttpRequest.prototype.open = function(method, url, async) {
this._url = url;
originalOpen.apply(this, arguments);
};
window.XMLHttpRequest.prototype.send = function() {
console.log('XHR request made:', this._url);
return originalSend.apply(this, arguments);
};
})();
这段代码通过重写 XMLHttpRequest 对象的 open 和 send 方法,在发送请求时记录请求的 URL。这种方式可以在所有浏览器中工作,但它会影响所有的 XHR 请求,可能对现有的代码造成影响。