前言
这两天重构博客的时候,发现果核新主题的Aerocore主题好像有一个站点性能的组件,就想抄下来。于是就让ai做了以下事情,并且解释了每一步的作用。下面就分享给大家。
核心代码
整个测量只需要一行:
const navigation = performance.getEntriesByType('navigation')[0];
performance.getEntriesByType('navigation') 返回一个数组,里面只有一个元素——PerformanceNavigationTiming 对象。这个对象记录了页面从开始导航到完全加载的每一个时间戳。
时间节点
navigation 对象包含一堆关键属性:
| 属性 | 含义 |
|---|---|
startTime | 页面导航开始的时间(时间原点) |
requestStart | 浏览器开始发送请求 |
responseStart | 收到服务器第一个字节(TTFB) |
responseEnd | 收到服务器最后一个字节 |
domInteractive | DOM 解析完成 |
domContentLoadedEventEnd | DOMContentLoaded 事件完成 |
loadEventEnd | 页面 load 事件完成 |
本站怎么用的
ai只给本站取了最关键的几个值:
const navigation = performance.getEntriesByType('navigation')[0];
// 完整页面加载时间(含 DNS、TCP、SSL、请求、DOM 解析、资源加载)
const loadTime = ((navigation.loadEventEnd - navigation.startTime) / 1000).toFixed(2);
document.getElementById('page-load').textContent = loadTime + ' 秒';
// 服务器响应延迟(TTFB)
const serverLatency = navigation.responseStart - navigation.requestStart;
loadEventEnd - startTime→ 页面总加载时长responseStart - requestStart→ 服务器处理延迟
就这么简单,没有任何第三方库,纯浏览器原生 API。
注意事项
performance.getEntriesByType('navigation') 必须在页面 load 事件之后调用,否则 loadEventEnd 还是 0:
window.addEventListener('load', () => {
setTimeout(() => {
const nav = performance.getEntriesByType('navigation')[0];
console.log('页面加载耗时:', (nav.loadEventEnd - nav.startTime) / 1000, '秒');
}, 0);
});
拆解更多指标
除了总时长,你还可以拆开看每个环节分别花了多久:
const nav = performance.getEntriesByType('navigation')[0];
console.log('DNS 查询:', nav.domainLookupEnd - nav.domainLookupStart, 'ms');
console.log('TCP 连接:', nav.connectEnd - nav.connectStart, 'ms');
console.log('SSL 握手:', nav.connectEnd - nav.secureConnectionStart, 'ms');
console.log('请求耗时:', nav.responseStart - nav.requestStart, 'ms');
console.log('响应下载:', nav.responseEnd - nav.responseStart, 'ms');
console.log('DOM 解析:', nav.domContentLoadedEventEnd - nav.responseEnd, 'ms');
console.log('页面总耗时:', nav.loadEventEnd - nav.startTime, 'ms');
兼容性
Navigation Timing API Level 2 兼容性很好:
- Chrome 57+
- Firefox 58+
- Safari 15+
- Edge 79+
基本上现代浏览器都支持。