How to trace JavaScript Performance using Navigation Timing API

JavaScriptFast websites, an universal demand, but not always achieved. If you are a web developer, is desired that you expend a couple of your time to care about this point.

This post complement my previous post: How to use Console Timing to Trace JavaScript Performance, and works as an introduction to use Navigation Timing API.

“The Navigation Timing API provides data that can be used to measure the performance of a website. Unlike other JavaScript-based mechanisms that have been for the same purpose this API can provide end-to-end latency data that can be more useful and accurate”.

The following graph illustrates the timing attributes defined by the PerformanceTiming interface and the PerformanceNavigation interface with or without redirect, respectively. Attributes underlined may not be available in navigation involving documents from different origins. User agents may perform internal processing in between timings, which allow for non-normative intervals between timings.

timing-overview-large_mini

For example, if you want to measure the user-perceived page loading time of a page you can use the next JavaScript code:

<html>
<head>
<script type="text/javascript">
// Add load event listener.
window.addEventListener("load", loadTime, false);
function loadTime() {
  // Get current time.
  var now = new Date().getTime();
  // Calculate page load time.
  var page_load_time = now - performance.timing.navigationStart;
  if (window.console) console.log("User-perceived page loading time" + page_load_time);
}

</head>
<body>
<!- More HTML here. -->
</body>
</html>

As definition:

  • navigationStart: Time after the previous document begins unload.

Or, in other words, tells us when the user initiated the page load, either by clicking a link, or entering it into their browser’s URL bar.

Now you have more tools, at least at client-side, to measure the performance of your pages.

More information:

Note: don’t forget to clean all console calls in your production code, also, check the browser compatibility (Mozilla MDN) since is not supported in all browsers.

Hope you find this information useful!