Home  >  Article  >  Web Front-end  >  Monitor front-end performance using HMTL5 API

Monitor front-end performance using HMTL5 API

黄舟
黄舟Original
2018-05-19 14:31:372424browse

The User Timing API can measure performance between two predefined markers in a web application. Developers only need to define the start and end markers of the measurement separately. The timing position can be marked through the function provided by the JavaScript object "".

var measuring_start = performance.now();

Through the "" function, you can get the timeout in the web application. Similar to this function is the Date object, which can also obtain the current timestamp. The main difference between the two is time accuracy. The w3c document for the return value of the now function clearly requires that it must be able to represent a millisecond value accurate to thousandths of a decimal place. In addition, the value returned by the now function is the number of milliseconds from the browser's "navigation start event (navigationStart)" to the present.

performance.now() 35438640.775000006 (new Date()).getTime() 1443063066478

If you want to analyze the loading performance of an image, you can set the second tag in the image's load event. The time it takes to load an image is the difference (in milliseconds) between the two variables "measure_start" and "measure_end".

<html> 
<head> 
<meta charset="utf-8" /> 
<title>test timing</title> 
</head> 
<body> 
<img src="http://cdn3.infoqstatic.com/statics_s2_20150922 -0305u1/styles/i/logo_bigger.jpg" alt="image" > 
<script type="text/javascript"> 
var measure_start = performance.now(); 
document.getElementsByTagName("img")[0].addEventListener ("load", function() { 
var measure_end = performance.now(); 
console.log("image load time: " + (measure_end - measure_start) + "ms"); 
}, false); 
</script> 
</body> 
</html>

After accessing this html, you can see the output in the console:

image load time: 24.395ms

At the same time, you can compare it with the loading time of the network tab in Chrome developer tools:

(Click to enlarge the image)

In addition to using the now function to directly obtain the timestamp, the Performance interface also provides functions. Developers can create and clear markers wherever they need to record time.

performance.mark("start"); … performance.mark("end");

The mark function does not return any value, but the marked data can be obtained later through the mark's name. If you want to calculate the difference between markers, you can do it with the "measure" function. This function requires three parameters, the first parameter defines the name of the difference, and the second and third variables specify the name of the marker. Likewise, this function does not return any value.

performance.measure("difference", "start", "end");

The above example calculates the difference between the two tags "start" and "end" and names the difference as "difference". It is important to note that the same names here will be recorded and will not be overwritten.

As mentioned earlier, the two functions mark and measure will not return any value. If you want to read the content of markers or measurements, you need to read it by calling "getEntries", "getEntriesByType" or "getEntriesByName" in the Performance interface. Among them, "getEntries" returns all tags (including resources loaded by web pages) and measurement results saved in the current performance object; the "getEntriesByType" function obtains the corresponding tags; the "getEntriesByName" function obtains the corresponding tags (or measurement results) by name. data. The return value of these functions is a list, including fields such as name, start time, time consumption, etc.

For example, if you want to obtain all markers or measurement results, you can obtain them through the "getEntriesByType" function:

performance.mark("start"); 
performance.mark("end"); 
performance.measure("difference", "start", "end"); 
var marks = performance.getEntriesByType("mark"); 
var measures = performance.getEntriesByType("measure"); 
console.log("===marks===:") marks.forEach(function(mark) { 
console.log(mark.name + ": " + mark.startTime); }) 
console.log("===measures===:") measures.forEach(function(measure){ 
console.log(measure.name + ": " + measure.duration) })

The output after execution in the browser (Chrome) console is:

===marks===: start: 6805479.590000001 end: 6805479.74 ===measures===: difference: 0.14999999944120646

You can see that in the returned object, the name field is the name of the set mark (measurement result). For the mark, you can get the mark time through startTime (like the now function mentioned above, the time returned here is also relative to navigationStart event), for the calculation result, the calculation result can be obtained through the duration field. In addition to the "mark" and "measure" types used in the above example, browsers (Chrome, Firefox, etc.) already support the "resource" type. In other words, these browsers have by default helped us measure the time it takes to load all external resources. For the html in the previous example (containing a reference to an image), if you execute the following js code in the browser console, you can directly see the time it takes to load the image:

performance.getEntriesByType("resource").forEach(function(r) { console.log(r.name + ": " + r.duration) })

The above code output (Chrome) For:

http://cdn3.infoqstatic.com/statics_s2_20150922- 0305u1/styles/i/logo_bigger.jpg: 21.696999901905656

This data is exactly the same as the time taken for this request recorded in the Network tab in Chrome developer tools.

If you want to obtain data directly through markers and measurement result names, you can obtain them through the getEntriesByName function. It should be noted that this function also returns an array of PerformanceEntry objects, and it needs to be iterated to obtain specific data.

Similarly, the Performance interface also provides an interface for removing tags. Previously created marks and measurement results can be deleted through the clearMarks and clearMeasures functions. Both functions receive an optional name parameter. If a name is passed in, the data with the specified name is deleted, otherwise the mark/measurement results are cleared.

performance.clearMarks(); 
performance.mark("start"); 
performance.mark("end"); 
var marks = performance.getEntriesByType("mark"); 
console.log("before clear:") marks.forEach(function(mark) { 
console.log(mark.name + ": " + mark.startTime); }) 
performance.clearMarks("start"); 
marks = performance.getEntriesByType("mark"); 
console.log("after clear:") marks.forEach(function(mark) { 
console.log(mark.name + ": " + mark.startTime); })

The output after the execution of the above code is:

before clear: start: 9080690.565000001 end: 9080690.575000001 after clear: end: 9080690.575000001

That is to say, after executing performance.clearMarks("start");, the "start" mark is cleared.

Browsing Timing API

The Browsing Timing API counts the timestamp of each node in the entire process from the beginning to the completion of loading of a web page. Different from the user timing API, the time of the browser timing API is a standard timestamp. The timestamp of each node is saved in the performance.timing object. For each node included, you can refer to the following figure:

(Click to enlarge the image)

console.log(performance.timing.domLoading); console.log(performance.timing.domComplete); 
console.log("load time: " + (performance.timing.domComplete - performance.timing.domLoading ));

For example, you can get the difference between domComplete (DOM construction is completed) and domLoading (DOM construction starts) value to calculate the time spent building the DOM tree.

In addition to the loading timestamps of each node saved in the timing object, the performance object also saves the and objects. It saves the load type and redirect times of the current page. Among them, the loading type types are:

TYPE_NAVIGATE(type == 0):通过点击链接、输入地址、表单提交、脚本初开启等方式加载

TYPE_RELOAD(type == 1):通过重新加载或者location.reload()操作加载

TYPE_BACK_FORWARD(type == 2):通过浏览器历史遍历操作加载

TYPE_RESERVED(type == 255):上面没有定义的其他方式

如直接打开一个页面,在控制台中执行:

console.log(performance.navigation.type);

上述脚本执行后,控制台会输出0,表示这是直接打开的一个页面。再次刷新页面,重新执行上面的JavaScript片段,则会输出1,表示这是一次重新加载。

performance.timing.redirectCount 记录了当前页面经历的重定向次数。

浏览器支持

用户计时API已经支持,如IE10+、Chrome 25+、Firefox 15+等,但是Safari等浏览器还不支持。对于浏览计时API,更多的浏览器已经,包括Chrome、Firefox、IE9+、Safari 8+等等。

以上就是使用HMTL5 API监控前端性能的内容,更多相关内容请关注PHP中文网(www.php.cn)!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn