在 JavaScript 中计算页面加载时间

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14341156/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 16:27:07  来源:igfitidea点击:

Calculating Page Load Time In JavaScript

javascriptloadsetinterval

提问by zingzing45

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,

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

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

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

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

有时,它会说一些更有意义的东西,例如 0.28 或 3.10。

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;

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

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

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.

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

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

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

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

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

回答by HaNdTriX

Why so complicated? When you can do:

为什么这么复杂?当你可以这样做时:

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

If you need more times check out the window.performance object:

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

console.log(window.performance);

Will show you the timing object:

将向您展示计时对象:

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

更多信息

回答by Bergi

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

永远不要使用setIntervalsetTimeout函数进行时间测量!它们是不可靠的,很可能是文档解析和显示过程中的 JS 执行调度延迟。

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

相反,使用该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>

回答by Samdeesh

The answer mentioned by @HaNdTriX is a great, but we are not sure if DOM is completely loaded in the below code:

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

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

This works perfectly when used with onload as:

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

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

Edit 1:Added some context to answer

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

Note:loadTimeis in milliseconds, you can divide by 1000 to get seconds as mentioned by @nycynik

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

回答by Samdeesh

It is hard to make a good timing, because the performance.dominteractive is miscalulated(anyway an interesting link for timing developers).

很难确定一个好的时机,因为performance.dominteractive 被错误地计算了(无论如何,对时序开发人员来说这是一个有趣的链接)。

When dom is parsed it still may load and execute deferred scripts. And inline scripts waiting for css (css blocking dom) has to be loaded also until DOMContentloaded. So it is not yet parsed?

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

And we have readystatechangeevent where we can look at readyStatethat unfortunately is missing "dom is parsed" that happens somewhere between "loaded" and "interactive".

我们有readystatechange事件,我们可以在那里查看readyState不幸的是缺少“dom is parsed”,它发生在“loaded”和“interactive”之间。

Everything becomes problematic when even not the Timing API gives us a time when dom stoped parsing HTML and starting The Endprocess. This standard say the first point has to be that "interactive" fires precisely after dom parsed! Both Chrome and FF has implemented it when document has finished loadingsometime after it has parsed. They seem to (mis)interpret the standars as parsing continues beyond deferred scripts executed while people misinterpret DOMContentLoaded as something hapen before defered executing and not after. Anyway...

当 dom停止解析 HTML 并启动The End进程时,即使 Timing API 没有给我们时间,一切都会变得有问题。这个标准说第一点必须是“交互式”在 dom解析后精确触发!当文档在解析后的某个时间完成加载时,Chrome 和 FF 都实现了它。他们似乎(错误)解释了标准,因为解析超出了执行的延迟脚本,而人们将 DOMContentLoaded 错误解释为延迟执行之前而不是之后发生的事情。反正...

My recommendation for you is to read about? Navigation Timing API. Or go the easy way and choose a oneliner of these, or run all three and look in your browsers console ...

我给你的建议是阅读?导航计时 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);

The time is in milliseconds after document started. I have verified with Navigation? Timing API.

文档开始后的时间以毫秒为单位。我已经通过导航验证了计时 API

To get seconds for exampe from the time you did var ti = performance.now()you can do parseInt(performance.now() - ti) / 1000

例如,从var ti = performance.now()你可以做的时间获得秒数parseInt(performance.now() - ti) / 1000

Instead of that kind of performance.now() subtractions the code get little shorter by User Timing APIwhere you set marksin your code and measurebetween marks.

而不是那种 performance.now() 减法,通过用户计时 API,您可以在代码中设置标记并在标记之间进行测量,从而缩短代码。