在JavaScript中计算页面加载时间

时间:2013-01-15 15:36:16

标签: javascript load setinterval

我正在尝试创建一个网页,当它开始加载时,使用Interval来启动计时器。

当页面完全加载时,它会停止计时器,

但99%的时间我的时间测量值为0.00或0.01,即使需要更长的时间。

偶尔,它会说某些更有意义的东西,比如.28或3.10。

如果有帮助,这是代码:

var hundredthstimer = 0;
var secondplace = 0;

function addinc(){

    hundredthstimer += 1;
    if (inctimer == 100){
        hundredthstimer = 0;
        secondplace += 1;
    }

}

var clockint = setInterval(addinc, 10);

function init(){
    var bconv1 = document.getElementById("bconverter1");
    var bconv2 = document.getElementById("bconverter2");

    $(bconv2).hide();

    clearInterval(clockint);

    if (inctimer.len !== 2){
        inctimer = "0" + inctimer;
    }
    alert(secondplace + "." + inctimer);
}
onload = init;

因此它基本上创建了一个名为“百分词”的变量,每10毫秒(。01秒)增加一个“1”。

然后,如果这个数字达到1000(1整秒),一个名为secondsplace的变量会增加1,因为这是它运行了多少个完整秒数。

然后,它会提醒秒位置,小数点和百分位数作为总加载时间。

但上述数字不正确的问题仍然存在。为什么呢?

4 个答案:

答案 0 :(得分:182)

为什么这么复杂?当你能做到:

var loadTime = window.performance.timing.domContentLoadedEventEnd- window.performance.timing.navigationStart;

如果您需要更多次,请查看window.performance对象:

console.log(window.performance);

会告诉你时间对象:

connectEnd                 Time when server connection is finished.
connectStart               Time just before server connection begins.
domComplete                Time just before document readiness completes.
domContentLoadedEventEnd   Time after DOMContentLoaded event completes.
domContentLoadedEventStart Time just before DOMContentLoaded starts.
domInteractive             Time just before readiness set to interactive.
domLoading                 Time just before readiness set to loading.
domainLookupEnd            Time after domain name lookup.
domainLookupStart          Time just before domain name lookup.
fetchStart                 Time when the resource starts being fetched.
loadEventEnd               Time when the load event is complete.
loadEventStart             Time just before the load event is fired.
navigationStart            Time after the previous document begins unload.
redirectCount              Number of redirects since the last non-redirect.
redirectEnd                Time after last redirect response ends.
redirectStart              Time of fetch that initiated a redirect.
requestStart               Time just before a server request.
responseEnd                Time after the end of a response or connection.
responseStart              Time just before the start of a response.
timing                     Reference to a performance timing object.
navigation                 Reference to performance navigation object.
performance                Reference to performance object for a window.
type                       Type of the last non-redirect navigation event.
unloadEventEnd             Time after the previous document is unloaded.
unloadEventStart           Time just before the unload event is fired.

Browser Support

More Info

答案 1 :(得分:67)

请勿使用setIntervalsetTimeout功能进行时间​​测量!它们不可靠,很可能在文档解析和显示期间的JS执行调度被延迟。

相反,使用Date object在页面开始加载时创建时间戳,并计算页面完全加载时的差异:

<doctype html>
<html>
    <head>
        <script type="text/javascript">
            var timerStart = Date.now();
        </script>
        <!-- do all the stuff you need to do -->
    </head>
    <body>
        <!-- put everything you need in here -->

        <script type="text/javascript">
             $(document).ready(function() {
                 console.log("Time until DOMready: ", Date.now()-timerStart);
             });
             $(window).load(function() {
                 console.log("Time until everything loaded: ", Date.now()-timerStart);
             });
        </script>
    </body>
</html>

答案 2 :(得分:30)

@HaNdTriX提到的答案很棒,但我们不确定DOM是否在下面的代码中完全加载:

var loadTime = window.performance.timing.domContentLoadedEventEnd- window.performance.timing.navigationStart; 

当与onload一起使用时,这非常有效:

window.onload = function () {
    var loadTime = window.performance.timing.domContentLoadedEventEnd-window.performance.timing.navigationStart; 
    console.log('Page load time is '+ loadTime);
}

编辑1:添加了一些上下文来回答

注意: loadTime以毫秒为单位,您可以除以1000以获得@nycynik所提及的秒数

答案 3 :(得分:0)

很难制定好的时机,因为the performance.dominteractive is miscalulated(无论如何对于时机开发人员来说都是一个有趣的链接)。

解析dom后,它仍然可以加载并执行延迟的脚本。并且,等待css(css阻止dom)的内联脚本也必须加载,直到DOMContentloaded。所以还没有解析?

我们有一个readystatechange事件,我们可以查看readyState,不幸的是,该事件缺少在“已加载”和“交互”之间发生的“已解析dom”。

当Timing API甚至没有给我们提供dom停止解析HTML并开始The End进程的时间时,一切都会变得问题。这个标准说的第一点必须是“交互式”在dom 解析后后立即触发!在解析后的某个时间document has finished loading,Chrome和FF都实现了它。他们似乎(误)解释了标准,因为解析超出了延迟执行的脚本的范围,而人们将DOMContentLoaded误认为是延迟执行之前而不是延迟执行之后的东西。反正...

我对您的建议是阅读Navigation Timing API。或者通过简单的方法选择其中一个,或者运行所有三个并在浏览器控制台中查看...

  document.addEventListener('readystatechange', function() { console.log("Fiered '" + document.readyState + "' after " + performance.now() + " ms"); });

  document.addEventListener('DOMContentLoaded', function() { console.log("Fiered DOMContentLoaded after " + performance.now() + " ms"); }, false);

  window.addEventListener('load', function() { console.log("Fiered load after " + performance.now() + " ms"); }, false);

文档开始后的时间(以毫秒为单位)。我已经通过Navigation​ Timing API进行了验证。

要从您进行var ti = performance.now()的时间起获得考试的时间,可以执行parseInt(performance.now() - ti) / 1000

而不是那种performance.now()减去,代码会缩短User Timing API,在代码中设置marks,在标记之间设置measure