developer tip

JavaScript에서 페이지로드 시간 계산

copycodes 2020. 12. 2. 21:31
반응형

JavaScript에서 페이지로드 시간 계산


로딩을 시작할 때 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'씩 증가하는 100 분의 1이라는 변수를 생성합니다.

그런 다음이 숫자가 1000 (1 초)에 도달하면 secondsplace라는 변수가 1만큼 올라갑니다.

그런 다음 총로드 시간으로 secondsplace, 소수점 및 100thsplace를 경고합니다.

그러나 위의 잘못된 숫자 문제는 여전히 존재합니다. 왜?


시간 측정을 위해 setInterval또는 setTimeout기능을 사용하지 마십시오 ! 신뢰할 수 없으며 문서 구문 분석 및 표시 중에 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>

왜 그렇게 복잡합니까? 할 수있는 경우 :

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.

브라우저 지원

더 많은 정보


@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 : 답변 할 컨텍스트 추가

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


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

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?

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

Everything becomes problematic when even not the Timing API gives us a time when dom stoped parsing HTML and starting The End process. 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 loading sometime 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...

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

  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.

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

Instead of that kind of performance.now() subtractions the code get little shorter by User Timing API where you set marks in your code and measure between marks.

참고URL : https://stackoverflow.com/questions/14341156/calculating-page-load-time-in-javascript

반응형