Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

The Web Performance APIs Reference

DZone's Guide to

The Web Performance APIs Reference

Performance is a big focus of the W3C Web Performance Working Group. Check out these APIs which provide a reference for web performance and W3C standards.

· Performance Zone ·
Free Resource

Sensu is an open source monitoring event pipeline. Try it today.

[This article appears in the DZone Guide to Performance & Monitoring – 2015 Edition. For additional information including insight from industry experts and luminaries, performance statistics and strategies, and an overview of how modern companies are handling application monitoring, download the guide below.]

The W3C Web Performance Working Group and browser vendors have acknowledged that performance is an important piece of web development, proposingnew standards and implementations manifested in performance APIs. The purpose of a (web) API is to provide better access to users’ browser and device. Performance APIs can ease the process of accurately measuring, controlling, and enhancing the users’ performance.

Each of the following performance APIs are in different stages of the W3C’s specification maturity process. You can see each spec’s stage next to their title. Visit this article for a concise graphic of all the performance APIs’ maturity levels.

NAVIGATION TIMING - W3C RECOMMENDATION

The Navigation Timing API helps measure real user data (RUM) such as bandwidth, latency, or the overall page load time for the main page. Here is how developers check the page’s performance via JavaScript through the PerformanceTiming interface: 

var page = performance.timing,
plt = page.loadEventStart - page.navigationStart,
console.log(plt); // Page load time (PTL) output for specific browser/user in ms;

Navigation timing covers the metrics of the entire page. To gather metrics about individual resources, you’ll use the Resource Timing API explained further down the list.

HIGH RESOLUTION TIMING - W3C RECOMMENDATION

The High Resolution Timing API supports floating point timestamps and provides measurements to a microsecond level of detail so that it is not subject to system clock skew or adjustments. 

var perf = performance.now();
// console output 439985.4570000316

PAGE VISIBILITY - W3C RECOMMENDATION

The visibilitychange event created by this spec is firedon document whenever the page gains or loses focus. This event is very helpful in programmatically determining the current visibility state of the page. For example, the API can be applied if your user has several browser tabs open and you don’t want specific content to execute (e.g playing a video, or rotating images in a carousel). 

document.addEventListener(‘visibilitychange’, function(event) {
if (document.hidden) {
// Page currently hidden.
} else {
// Page currently visible.
} });

RESOURCE TIMING - CANDIDATE RECOMMENDATION

The Resource Timing API lets you dig deeper into understanding the behavior of each individual resource in a page. As an example, let’s pick the DZone logo, and retrieve the total loading time in ms: 

var img = window.performance.getEntriesByName(“http:// cdn.dzone.com/static/images/TOP_NAV_LOGO.png”)[0]; var total = parseInt(img.responseEnd - img.startTime); console.log(total); // output e.g. 281 (in ms)

Beyond the main page’s performance (via the Navigation Timing API), you can also track real user experiences on a more granular basis (i.e. resource basis).

PERFORMANCE TIMELINE - CANDIDATE RECOMMENDATION

The Performance Timeline specification defines a unifying interface to retrieve the performance data collected via Navigation Timing, Resource Timing, and User Timing. 

// gets all entries in an array
var perf = performance.getEntries(); for (var i = 0; i < perf.length; i++) {
console.log(“Asset Type: “ + perf[i].name + “ Duration: “ + perf[i].duration + “\n”); }

BATTERY STATUS - CANDIDATE RECOMMENDATION

This API provides access to the battery status of your user’s battery-driven device. The specific metrics you can access are charging, chargingTime, dischargingTime and level. Events can also be fired based on these statuses: 

var battery = navigator.battery || navigator. webkitBattery || navigator.mozBattery || navigator. msBattery;
if (battery) {
console.log(“Battery charging? “ + battery.charging ? “Yes” : “No”);
console.log(“Battery level: “ + battery.level * 100 + “ %”);
console.log(“Battery charging time: “ + battery. chargingTime + “ seconds”);
console.log(“Battery discharging time: “ + battery. dischargingTime + “ seconds”);
});

USER TIMING - CANDIDATE RECOMMENDATION

With the User Timing API, you can set markers to measure specific blocks or functions of your application. The calculated elapsed time can be an indicator of good or bad performance. 

performance.mark(“start”);
loadSomething();
performance.mark(“end”); performance.measure(“measureIt”, “start”, “end”); var markers = performance.getEntriesByType(“mark”); var measurements = performance. getEntriesByName(“measureIt”); console.log(“Markers: “, markers); console.log(“Measurements: “, measurements); function loadSomething() {
// some crazy cool stuff here :)
console.log(1+1);
}

BEACON - WORKING DRAFT

With the beacon API, you can send analytics or diagnostic code from the user agent to the server. By sending this asynchronously, you won’t block the rendering of the page. 

navigator.sendBeacon(“http://mywebserver.com”, ‘any information you want to sent’);

ANIMATION TIMING - EDITOR’S DRAFT

Instead of using setTimeOut or setInterval tocreate animations, this spec will introduce the requestAnimationFrame. This method grants the browser control over how many frames it can render; aiming to match the screen’s refresh rate (usually 60fps) will result in a jank-free experience. It can also throttle animations if the page loses visibility (e.g., the user switches tabs), dramatically decreasing power consumption and CPU usage.

Check out Microsoft’s demo page comparing setTimeOut with requestAnimationFrame.

RESOURCE HINTS - EDITOR’S DRAFT

Predictive browsing is a great way to serve your userswith exactly what they want to see or retrieve next. “Pre- browsing” refers to an attempt to predict the users’ activity with your page—i.e. is there anything we can load prior to the user requesting it? This spec will allow developers to give the User Agent hints on the download priority of a resource.

The following pre-browsing attribu tes are meant to help you with pre-loading assets on your page. 

<link rel=”dns-prefetch” href=”//host_to_resolve.com”> <link rel=”subresource” href=”/javascript/mydata. json”>
<linkrel=”prefetch” href=”/images/labrador.jpg”> <link rel=”prerender” href=”//example.org/page_2. html”>

FRAME TIMING (NOT SUPPORTED YET) - EDITOR’S DRAFTThis specification defines an interface to help web developers measure the frame performance of their applications by giving them access to measurements like frames per second and time to frame. – W3C

NAVIGATION ERROR LOGGING (NOT SUPPORTED YET) - EDITOR’S DRAFTThis specification defines an interface to store and retrieve error data related to the previous navigations of a document. – W3C

BROWSER SUPPORT

For a chart of the browser support for all of these standards, visit this blog post and scroll down to Browser support overview. Your best method for keeping up with upcoming standards is to subscribe to the Web Performance Working Group mailing list for any performance-related updates. 

DOWNLOAD YOUR FREE COPY TODAY

Sensu: workflow automation for monitoring. Learn more—download the whitepaper.

Topics:
java ,api ,w3c ,performance ,apis

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}