window.addEventListener('load', (event) => {
// Time to Interactive
let timing = performance.getEntriesByType('navigation')[0];
// let timing = performance.timing
console.log(timing.domInteractive);
console.log(timing.fetchStart);
let diff = timing.domInteractive - timing.fetchStart;
console.log("TTI: " + dff);
})
观察长任务(long tasks)
// 通过 PerformanceObserver 得到所有的 long task 对象
const observer = new PerformanceObserver((list) => {
for (const entry of list.getEntries()) {
console.log(entry)
}
})
// 监听 long task
observer.observe({entryTypes: ['longtask']})
监听页面可见性的状态
let vEvent = 'visibilitychange';
if (document.webkitHidden != undefined) {
// webkit prefix detected
vEvent = 'webkitvisibilitychange';
}
function visibilityChanged() {
if (document.hidden || document.webkitHidden) {
console.log("Web page is hidden.")
} else {
console.log("Web page is visible.")
}
}
document.addEventListener(vEvent, visibilityChanged, false);
通过监听页面可见性的状态可以判断用户是否在看当前页面,可以做一些处理,比如视频暂停,保存状态等等
判断用户网络状态
var connection = navigator.connection || navigator.mozConnection || navigator.webkitConnection;
var type = connection.effectiveType;
function updateConnectionStatus() {
console.log("Connection type changed from " + type + " to " + connection.effectiveType);
type = connection.effectiveType;
}
connection.addEventListener('change', updateConnectionStatus);
得分点
加载速度、第一个请求响应时间、页面加载时间、交互动作的反馈时间、帧率FPS、异步请求完成时间 Lighthouse、Throttling 、Performance、Network、WebPageTest
参考答案
标准回答
常用的性能优化指标
使用性能测量工具进行量化
加分回答
常用的性能测量API
延伸阅读
计算首次可交互时间距离
window.addEventListener('load', (event) => { // Time to Interactive let timing = performance.getEntriesByType('navigation')[0]; // let timing = performance.timing console.log(timing.domInteractive); console.log(timing.fetchStart); let diff = timing.domInteractive - timing.fetchStart; console.log("TTI: " + dff); })观察长任务(long tasks)
// 通过 PerformanceObserver 得到所有的 long task 对象 const observer = new PerformanceObserver((list) => { for (const entry of list.getEntries()) { console.log(entry) } }) // 监听 long task observer.observe({entryTypes: ['longtask']})监听页面可见性的状态
let vEvent = 'visibilitychange'; if (document.webkitHidden != undefined) { // webkit prefix detected vEvent = 'webkitvisibilitychange'; } function visibilityChanged() { if (document.hidden || document.webkitHidden) { console.log("Web page is hidden.") } else { console.log("Web page is visible.") } } document.addEventListener(vEvent, visibilityChanged, false);通过监听页面可见性的状态可以判断用户是否在看当前页面,可以做一些处理,比如视频暂停,保存状态等等
判断用户网络状态
var connection = navigator.connection || navigator.mozConnection || navigator.webkitConnection; var type = connection.effectiveType; function updateConnectionStatus() { console.log("Connection type changed from " + type + " to " + connection.effectiveType); type = connection.effectiveType; } connection.addEventListener('change', updateConnectionStatus);通过判断用户网络状态,可以做一些针对性的加载,比如用户网络状态好,就可以加载一些更加高清的图片,反之加载一些质量更差的图片等等。