Search code examples
javascriptwindow-object

Why does window.performance.timing.domContentLoadedEventStart return 0


Below is my js function code.

console.log(window.performance.timing);
console.log(window.performance.timing.domContentLoadedEventStart);

When i run the above code by running my js file, window.performance.timing returns an object in which domContentLoadedEventStart has some value. But when i tried to print window.performance.timing.domContentLoadedEventStart it returns 0.

Not sure what is happening. Can somebody explain me.


Solution

  • window.performance.timing

    This property has a PerformanceTiming object describing your page.

    PerformanceTiming.domContentLoadedEventStart

    The PerformanceTiming.domContentLoadedEventStart property has a value representing the moment right before the parser sent the DOMContentLoaded event, in miliseconds since the UNIX epoch.

    DOMContentLoaded event

    The DOMContentLoaded event is fired when the initial HTML document has been completely loaded and parsed, without waiting for stylesheets, images, and subframes to finish loading.

    The reason why window.performance.timing.domContentLoadedEventStart gave you 0

    Your script was executed before the DOMContentLoaded event occurred, so the moment right before the parser sent the DOMContentLoaded event, was unknown at that time.

    https://html.spec.whatwg.org/multipage/scripting.html

    To prevent it

    To prevent PerformanceTiming.domContentLoadedEventStart from being 0, you have to refer it after the DOMContentLoaded event occurs. Try this one:

    document.addEventListener("DOMContentLoaded", event => {
        console.info("DOM fully loaded and parsed.");
        console.info(window.performance.timing.domContentLoadedEventStart);
    });
    

    or

    <script defer src="...">
    

    .