--- title: Using Navigation Timing slug: Web/API/Navigation_timing_API/Using_Navigation_Timing tags: - Navigation Timing - Navigation Timing API - Optimization - Performance translation_of: Web/API/Navigation_timing_API/Using_Navigation_Timing ---
{{DefaultAPISidebar("Navigation Timing")}}
Navigation Timing 接口使你可以轻松获取详细且高度准确的计时信息,以帮助从你的网站代码或资源隔离出性能问题。与其他工具或库不同,Navigation Timing 接口使你可以收集这些只有浏览器才能提供的信息,其准确性要比其他技术大大提高。它还具有能够提供用户所感知的计时信息而不是与用户体验无关的数据的优势。
使用该API就像使用{{domxref("window.performance")}}获取{{domxref("Performance")}}对象并在返回的对象中查找所需内容一样简单。比如,为了测量页面的感知到的加载时间:
window.addEventListener("load", function() { let now = new Date().getTime(); let loadingTime = now - performance.timing.navigationStart; document.querySelector(".output").innerText = loadingTime + " ms"; }, false);
在发生{{event("load")}}事件时执行的该代码从当前时间中减去浏览器导航开始时记录的时间({{domxref("PerformanceTiming.navigationStart", "performance.timing.navigationStart")}}),并通过将该信息插入到元素中,输出到屏幕。
<div class="output"> </div>
.output { border: 1px solid #bbb; font: 16px "Open Sans", "Helvetica", "Arial", sans-serif; }
结合适当的HTML和CSS,结果就是:
{{EmbedLiveSample("Collecting_timing_information", 500, 80)}}
列出的值适用于上面展示了示例的{{HTMLElement("iframe")}}。
你可以在{{domxref("PerformanceTiming")}}中查找可用的计时值的列表,请参见{{domxref("PerformanceTiming")}}接口的“属性”部分。
为了将从 {{domxref("PerformanceTiming")}}获取到的计时信息放入正确的观点,你需要更多地了解发生了哪种加载操作。特别是你需要知道:
此信息由{{domxref("Performance.navigation")}}属性提供,该属性返回包含所需信息的{{domxref("PerformanceNavigation")}}对象。
让我们将此信息添加到上面的示例中。 新代码如下所示:
window.addEventListener("load", function() { let now = new Date().getTime(); let loadingTime = now - performance.timing.navigationStart; output = "Load time: " + loadingTime + " ms<br/>"; output += "Navigation type: "; switch(performance.navigation.type) { case PerformanceNavigation.TYPE_NAVIGATE: output += "Navigation"; break; case PerformanceNavigation.TYPE_RELOAD: output += "Reload"; break; case PerformanceNavigation.TYPE_BACK_FORWARD: output += "History"; break; default: output += "Unknown"; break; } output += "<br/>Redirects: " + performance.navigation.redirectCount; document.querySelector(".output").innerHTML = output; }, false);
这通过查看performance.navigation
对象的内容来修改了前面的示例。{{domxref("PerformanceNavigation.type", "performance.navigation.type")}}指示发生了哪种加载操作:导航,重新加载或浏览器历史记录的切换。我们还从{{domxref("PerformanceNavigation.redirectCount", "performance.navigation.redirectCount")}}获取导航期间发生的重定向次数。就像以前的页面加载时间一样,此信息通过插入到具有"output"
类的元素中输出到屏幕上。
<div class="output"> </div>
.output { border: 1px solid #bbb; font: 16px "Open Sans", "Helvetica", "Arial", sans-serif; }
使用此代码后,结果如下所示:
{{EmbedLiveSample("Determining_navigation_type", 500, 120)}}
列出的值适用于展示示例的 {{HTMLElement("iframe")}} 。