一、window.performance 火狐报错
在Firefox浏览器中,当我们使用 window.performance
时,可能会出现“window.performance is undefined”错误。这是因为Firefox没有实现 window.performance
属性。但是,我们可以使用Firefox专用的 PerformanceTiming
对象,其属性和 window.performance
相同,以兼容Firefox。
if (window.performance) {
console.log("window.performance is available");
}
else {
console.log("window.performance is not available");
}
if (typeof window.PerformanceTiming !== 'undefined') {
console.log("PerformanceTiming is available");
}
else {
console.log("PerformanceTiming is not available");
}
二、window.performance.memory
该属性返回一个对象,其中包含有关页面的内存使用情况的信息。我们可以使用它来检测内存泄漏。
console.log(window.performance.memory);
三、window.performance ajax可以吗
可以。window.performance
可以用来测量 Ajax 请求的性能。
var xhr = new XMLHttpRequest();
xhr.open('GET', 'http://example.com/api/data', true);
var t0 = performance.now();
xhr.onload = function() {
var t1 = performance.now();
console.log('Request took ' + (t1 - t0) + ' milliseconds.');
};
xhr.send();
四、window.performance.mark
该方法可以用于在代码中标记时间点。我们可以使用它来测量代码执行时间。
performance.mark("start");
//代码执行
performance.mark("end");
performance.measure("Execution Time", "start", "end");
var measures = performance.getEntriesByType("measure");
console.log(measures[0].duration);
五、window.performance.n
该方法返回 performance entries 的数量。
var n = performance.getEntries().length;
console.log(n);
六、window.performance.timing
该属性返回一个 PerformanceTiming
对象,该对象包含有关页面加载过程中各种时间的信息,例如页面加载时间、解析时间等。以下是 PerformanceTiming
对象中的一些属性:
- navigationStart
- unloadEventStart
- unloadEventEnd
- redirectStart
- redirectEnd
- fetchStart
- domainLookupStart
- domainLookupEnd
- connectStart
- connectEnd
- secureConnectionStart
- requestStart
- responseStart
- responseEnd
- domLoading
- domInteractive
- domContentLoadedEventStart
- domContentLoadedEventEnd
- domComplete
- loadEventStart
- loadEventEnd
我们可以使用
PerformanceTiming
对象来定位渲染过程中的瓶颈。
var timing = performance.timing;
console.log(timing.loadEventEnd - timing.navigationStart);
七、window.performance.now
该方法返回从性能测量开始经过的毫秒数。它是用于获取当前时间的最简单和最精确的方法。
var t0 = performance.now();
//代码执行
var t1 = performance.now();
console.log("Code Execution Time: " + (t1 - t0) + "milliseconds.");
八、window.performance.mark 报错
在使用 window.performance.mark
时,可能会出现“Cannot read property 'mark' of undefined”错误。这是因为浏览器不支持在 window.performance
中使用 mark
方法。相反,我们应该在 Performance
实例中使用它。
var perf = window.performance || window.webkitPerformance || window.msPerformance || window.mozPerformance;
if (perf) {
perf.mark("start");
//代码执行
perf.mark("end");
perf.measure("Execution Time", "start", "end");
var measures = perf.getEntriesByType("measure");
console.log(measures[0].duration);
}
九、window.performance.getEntries
该方法返回一个 PerformanceEntry
对象的数组,该数组包含性能测量的结果。
var entries = performance.getEntries();
console.log(entries);
以上是对 window.performance
的多方位阐述,如何使用它来测量页面性能、代码执行时间以及如何使用它来定位瓶颈。它非常有用,可以帮助我们提高用户体验,发现和解决性能问题。