如何获取精确的页面加载时长
@邹立杰
解决问题
Solution 1: KMD
window.addEventListener('load', () => {
if (window.KMD) window.KMD.show();
});
2s首屏,不错哦
问题
是不是我们对 Load 事件理解有问题?
The load event is fired when the whole page has loaded, including all dependent resources such as stylesheets and images. —— MDN
Load
-
n.
负荷; 负担; 装载; 工作量
-
vt.
使担负; 装填; 把…装入或装上; 装满,堆积
-
vi.
加载; 装载; 装货;
load == download
'加载' vs Load
Gain Accurate Time Of Rendering Page ?
Time Of
Rendering Page
广义上:
从浏览器进行 navigationStart 、解析DNS、发送请求到渲染页面完成的整个过程所需要的时间。
狭义上:
从浏览器解析 JavaScript 然后将其执行,到页面渲染完成的整个时间,其实这个时间应叫做「页面渲染耗时」。
Solution 2:Date.now()
var start = Date.now();
// ......
// 我在疯狂的执行呀
// ....
var end = Date.now();
console.log(`time of rendering page is ${start - end} millsecond`);
如何监控页面已渲染完成?
document.body.addEventListener('DOMSubtreeModified', () => {
debounce(fn, 800);
});
var start = Date.now();
function fn() {
var end = Date.now();
console.log(`time of rendering page is ${end - start} millsecond`);
}
噢😎
我们还有副标题
Date API
从1970年1月1号至今的毫秒数
受系统时间约束
靠谱?
High Resolution
sub-millisecond
Monotonic
it’s not affected by the system
This specification defines an API that provides the time origin, and current time in sub-millisecond resolution, such that it is not subject to system clock skew or adjustments.
Solution 3
window.performance.mark('rendering start');
window.performace.mark('rendering end');
window.performance.measure('render time', 'rendering start', 'rendering end');
window.performance.mark('render start');
document.body.addEventListener('DOMSubtreeModified', () => {
debounce(fn, 800);
});
function fn() {
window.performance.mark('render end');
window.performance.measure('render time', 'render start', 'render end');
const { duration } = window.performance.getEntriesByType('measure')[0];
console.log(`page render time is ${duration - 800}`);
}
还记得我们的定义吗?
至此,完成了狭义的时长🥶
广义的呢?
console.log(window.performance.timing)
什么你还想获取各项资源的加载时长?
performance.getEntriesByType("resource").forEach(function(r) {
console.log(r.name + ": " + r.duration)
})
solution 3 Problem
Wrap-up
How To Gain Accurate Time Of Rendering Page
By baiji
How To Gain Accurate Time Of Rendering Page
- 827