在JavaScript中计算页面加载时间 [英] Calculating Page Load Time In JavaScript

查看:166
本文介绍了在JavaScript中计算页面加载时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am trying to make a webpage that, when it starts loading, uses an Interval to start a timer.

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

When the page fully loads, it stops the timer,

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

but 99% of the time i get time measurements of 0.00 or 0.01 even if it takes longer.

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

Occasionally, it says something that makes more sense like .28 or 3.10 at some times.

如果有帮助,这是代码:

Here is the code if it helps:

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毫秒增加一个1(.01秒)。

So it basically creates a variable called hundredthstimer which is increased by '1' every 10 miliseconds(.01 seconds).

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

Then, if this number reaches 1000(1 full second), a variable called secondsplace goes up by 1, since that is how many full seconds it has run for.

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

Then, it alerts secondsplace, a decimal point, and hundredthsplace as the total load time.

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

But the problem above with incorrect numbers still exists. Why?

推荐答案

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

Don't ever use the setInterval or setTimeout functions for time measuring! They are unreliable, and it is very likely that the JS execution scheduling during a documents parsing and displaying is delayed.

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

Instead, use the Date object to create a timestamp when you page began loading, and calculate the difference to the time when the page has been fully loaded:

<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>

这篇关于在JavaScript中计算页面加载时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆