为什么window.performance.timing.domContentLoadedEventStart返回0

时间:2017-10-24 09:14:00

标签: javascript window-object

以下是我的js功能代码。

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

当我通过运行js file运行上述代码时,window.performance.timing会返回object domContentLoadedEventStart有一些值的window.performance.timing.domContentLoadedEventStart。但是当我试图打印$datetime1 = new DateTime('2009-10-11'); $datetime2 = new DateTime('2009-10-10'); $difference = $datetime1->diff($datetime2); echo formatOutput($difference); function formatOutput($diff){ /* function to return the highrst defference fount */ if(!is_object($diff)){ return; } if($diff->y > 0){ return $diff->y .(" year".($diff->y > 1?"s":"")." ago"); } if($diff->m > 0){ return $diff->m .(" month".($diff->m > 1?"s":"")." ago"); } if($diff->d > 0){ return $diff->d .(" day".($diff->d > 1?"s":"")." ago"); } if($diff->h > 0){ return $diff->h .(" hour".($diff->h > 1?"s":"")." ago"); } if($diff->i > 0){ return $diff->i .(" minute".($diff->i > 1?"s":"")." ago"); } if($diff->s > 0){ return $diff->s .(" second".($diff->s > 1?"s":"")." ago"); } } 时,它返回0.

不确定发生了什么。有人可以解释一下。

1 个答案:

答案 0 :(得分:1)

window.performance.timing

此属性有一个描述您页面的PerformanceTiming对象。

PerformanceTiming.domContentLoadedEventStart

PerformanceTiming.domContentLoadedEventStart属性的值表示解析器发送DOMContentLoaded事件之前的时刻,自UNIX纪元以来的毫秒数。

DOMContentLoaded事件

初始HTML文档完全加载并解析后会触发DOMContentLoaded事件,而无需等待样式表,图像和子帧完成加载。

window.performance.timing.domContentLoadedEventStart为您提供0

的原因

您的脚本在DOMContentLoaded事件发生之前执行,因此在解析器发送DOMContentLoaded事件之前的那一刻,当时是未知的。

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

为了防止它

要防止PerformanceTiming.domContentLoadedEventStart成为0,您必须在DOMContentLoaded事件发生后引用它。试试这个:

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

<script defer src="...">