在JavaScript中计算页面加载时间

zin*_*g45 60 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;
Run Code Online (Sandbox Code Playgroud)

所以它基本上创建了一个名为百分时的变量,每10毫秒(.01秒)增加1.

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

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

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

HaN*_*riX 192

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

var loadTime = window.performance.timing.domContentLoadedEventEnd- window.performance.timing.navigationStart;
Run Code Online (Sandbox Code Playgroud)

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

console.log(window.performance);
Run Code Online (Sandbox Code Playgroud)

会告诉你时间对象:

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.
Run Code Online (Sandbox Code Playgroud)

浏览器支持

更多信息

  • var loadTime = window.performance.timing.domComplete- window.performance.timing.navigationStart; 为什么这不起作用?这应该给出加载时间,就像你提到的那样给出了DOMContentLoaded时间.我试过这个,它给了我 - (navigationStart) (3认同)
  • 两者相同是有道理的,因为domContentLoadedEventEnd和domComplete是相同的。尝试:document.addEventListener(“ DOMContentLoaded”,function(event){//在这里进行计算}); (也许您的jQuery不知何故被弄乱了) (2认同)

Ber*_*rgi 67

不要使用setIntervalsetTimeout函数进行时间测量!它们是不可靠的,并且很可能在文档解析和显示期间的JS执行调度被延迟.

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

<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>
Run Code Online (Sandbox Code Playgroud)

  • 为什么这个答案如此受欢迎?代码使用jQuery,在加载过程中肯定不会出现太晚了吗? (5认同)
  • @AlexanderWigmore:我也不知道为什么它如此受欢迎,我想这只是从问题的11k观点出发。它使用jQuery绝对没有问题,因为无论如何它都需要测量加载脚本文件的时间。当然,您可以不使用jQuery而手动附加DOMready和window.onload的侦听器。 (2认同)

Sam*_*esh 32

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

var loadTime = window.performance.timing.domContentLoadedEventEnd- window.performance.timing.navigationStart; 
Run Code Online (Sandbox Code Playgroud)

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

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

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

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

  • 是的,返回时间,以毫秒为单位.您可以除以1000来获得秒数.((window.performance.timing.domComplete-window.performance.timing.navigationStart)/ 1000)+"sec."; (3认同)
  • 这会以毫秒为单位吗? (2认同)
  • 当您开始在浏览器中加载页面时,`navigationStart`开始.这有一个优点,它包括所有服务器端处理时间(对于主HTML页面)和任何网络延迟 - 这是不可能通过在页面开头的简单javascript计时器计算 (2认同)