我正在使用 Navigation timing object计算导航开始和加载事件结束之间的整页延迟。
我的目标是在加载事件完成时获得 performance.timing.loadEventEnd - performance.timing.navigationStart;
。
但是,在加载事件中调用此代码,无法测量加载事件结束。所以,我需要推迟它并在加载事件之外运行。
这是我的要求
- 在加载事件结束后调用
myfunction
。 - 我不想使用像
setTimeout
这样的计时功能。如果setTimeout
保证在其他加载事件中不唤醒,就可以使用。 - 我不想计算
load
事件中的时间延迟。 (比如在load
事件的顶部调用new Date().getTime()
或performance.now()
,并在之前再次调用它完成并减去它。)因为我使用了一堆也调用加载事件的第三方库。我无法处理所有这些。 - 应该在跨浏览器环境下工作,IE>=10
$(window).ready(function(){
console.log("domContentLoadedEventStart: "
+performance.timing.domContentLoadedEventStart);
console.log("domContentLoadedEventEnd: "
+performance.timing.domContentLoadedEventEnd);
});
// result:
// > domContentLoadedEventStart: 1451979544555
// > domContentLoadedEventEnd: 0
$(window).load(function(){
console.log("domcomplete: "+performance.timing.domComplete);
console.log("loadEventStart: "+performance.timing.loadEventStart);
console.log("loadEventEnd: "+performance.timing.loadEventEnd);
});
// result:
// > domcomplete: 1451979906417
// > loadEventStart: 1451979906417
// > loadEventEnd: 0
编辑
我已经测试了这个套件。此测试用例旨在在加载函数回调期间唤醒 setTimeout
。
// myfunction which will be called by setTimeout in firstLoadCallback.
function myfunction(){
console.log("called myfunction");
}
// first load callback
$(window).load(function firstLoadCallback(){
var startTicks = performance.now();
// register myfunction with setTimeout
setTimeout(myfunction, 0);
// sleep +500ms
while(performance.now() - startTicks < 500){
;
}
var diffTicks = performance.now() - startTicks;
console.log("first ticks: "+diffTicks);
});
// second load callback
$(window).load(function secondLoadCallback(){
var startTicks = performance.now();
// sleep +500ms
while(performance.now() - startTicks < 500){
;
}
var diffTicks = performance.now() - startTicks;
console.log("second ticks: "+diffTicks);
});
// third callback from other file: other-file.js
$(window).load(function thirdLoadCallback(){
var startTicks = performance.now();
// sleep +500ms
while(performance.now() - startTicks < 500){
;
}
var diffTicks = performance.now() - startTicks;
console.log("third ticks: "+diffTicks);
});
// result:
// first ticks: 500.005
// second ticks: 500.0050000000001
// third ticks: 500.0049999999999
// called myfunction
从这个结果来看,由setTimeout
注册的回调在函数调用树结束之前不会被唤醒。如果这个结果保证跨浏览器工作,@BenjaminGruenbaum 的回答可能是正确的。
我将发布另一个关于它的问题。
最佳答案
除了嵌套加载事件和 setTimeout 之外,您别无选择。
$(window).load(function(){
setTimeout(function() {
// your above code goes here
}, 0); // 0, since we just want it to defer.
});
// or without jQuery:
window.addEventListener("load", function() { // IE9+
setTimeout(function() {
// your above code goes here
}, 0); // 0, since we just want it to defer.
});
关于javascript - 加载事件结束后调用函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34606567/