一、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的多方位闡述,如何使用它來測量頁面性能、代碼執行時間以及如何使用它來定位瓶頸。它非常有用,可以幫助我們提高用戶體驗,發現和解決性能問題。
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-hant/n/286641.html