1

The Web Performance APIs Reference

 2 years ago
source link: https://dzone.com/articles/web-performance-apis-reference
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

Each of the following performance APIs is 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.

The use of APIs to Boost Performance

If you are actively wondering why you need to look at getting APIs into your system in the first place, you are not alone. Plenty of people have questioned what is so important about APIs and why it is that they need to focus on them, to begin with. They have a multitude of questions, but the answer all boils down to the fact that APIs provide real data that programmers can use to judge their own performance. 

The reality is, that most programmers are numbers-oriented people, and they like to see how their work contributes to the overall project that they are attempting to complete. APIs allow them to track those figures much more easily over time, and this is precisely what needs to be done to get projects done properly. Every API that they use contributes to great project success overall. 

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 Performance Timing 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 visibility change event created by this spec is fired on the 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 to create 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 users with 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 attributes 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 DRAFT

This 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 DRAFT

This 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


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK