Monitor front-end performance using HMTL5 API
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)!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

PHP and ManticoreSearch Development Guide: Quickly Create a Search API Search is one of the indispensable features in modern web applications. Whether it is an e-commerce website, social media platform or news portal, it needs to provide an efficient and accurate search function to help users find the content they are interested in. As a full-text search engine with excellent performance, ManticoreSearch provides us with a powerful tool to create excellent search APIs. This article will show you how to

How to crawl and process data by calling API interface in PHP project? 1. Introduction In PHP projects, we often need to crawl data from other websites and process these data. Many websites provide API interfaces, and we can obtain data by calling these interfaces. This article will introduce how to use PHP to call the API interface to crawl and process data. 2. Obtain the URL and parameters of the API interface. Before starting, we need to obtain the URL of the target API interface and the required parameters.

Title: How to deal with Laravel API error problems, specific code examples are needed. When developing Laravel, API errors are often encountered. These errors may come from various reasons such as program code logic errors, database query problems, or external API request failures. How to handle these error reports is a key issue. This article will use specific code examples to demonstrate how to effectively handle Laravel API error reports. 1. Error handling in Laravel

Oracle is a world-renowned database management system provider, and its API (Application Programming Interface) is a powerful tool that helps developers easily interact and integrate with Oracle databases. In this article, we will delve into the Oracle API usage guide, show readers how to utilize data interface technology during the development process, and provide specific code examples. 1.Oracle

ReactAPI Call Guide: How to interact with and transfer data to the backend API Overview: In modern web development, interacting with and transferring data to the backend API is a common need. React, as a popular front-end framework, provides some powerful tools and features to simplify this process. This article will introduce how to use React to call the backend API, including basic GET and POST requests, and provide specific code examples. Install the required dependencies: First, make sure Axi is installed in the project

OracleAPI integration strategy analysis: To achieve seamless communication between systems, specific code examples are required. In today's digital era, internal enterprise systems need to communicate with each other and share data, and OracleAPI is one of the important tools to help achieve seamless communication between systems. This article will start with the basic concepts and principles of OracleAPI, explore API integration strategies, and finally give specific code examples to help readers better understand and apply OracleAPI. 1. Basic Oracle API

Development suggestions: How to use the ThinkPHP framework for API development. With the continuous development of the Internet, the importance of API (Application Programming Interface) has become increasingly prominent. API is a bridge for communication between different applications. It can realize data sharing, function calling and other operations, and provides developers with a relatively simple and fast development method. As an excellent PHP development framework, the ThinkPHP framework is efficient, scalable and easy to use.

In the world of data-driven applications and analytics, APIs (Application Programming Interfaces) play a vital role in retrieving data from various sources. When working with API data, you often need to store the data in a format that is easy to access and manipulate. One such format is CSV (Comma Separated Values), which allows tabular data to be organized and stored efficiently. This article will explore the process of saving API data to CSV format using the powerful programming language Python. By following the steps outlined in this guide, we will learn how to retrieve data from the API, extract relevant information, and store it in a CSV file for further analysis and processing. Let’s dive into the world of API data processing with Python and unlock the potential of the CSV format
