当前位置:网站首页>Performance optimization
Performance optimization
2022-07-22 09:33:00 【28 hours a day】
https://www.cnblogs.com/tugenhua0707/p/10982332.html This article is reprinted.
Performance --- Front end performance monitoring
</div>
Read the directory
- One : What is? Performance?
- Two : Use performance.timing To calculate the value
- 3、 ... and : How to optimize the front-end performance ?
- Four :Performance Medium method
- 5、 ... and : Use performane Write gadgets
One : What is? Performance?
Performance It's front-end performance monitoring API. It can detect the performance in the page ,W3C The performance team introduced a new API, It can detect white screen time 、 First screen time 、 User operable time nodes , The total download time of the page 、DNS The time of the query 、TCP Link time, etc . So let's learn about this API.
So before studying , The main test points of front-end performance are as follows :
White screen time : From the time we open the website to the time when the content is rendered .
First screen time : Time node after rendering the first screen content .
Users can operate time nodes :domready Trigger node .
Total download time :window.onload The trigger node of .
We're in html Let's use it simply performance The basic code of : As shown in the following code :
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>performance demonstration </title> </head> <body> <script type="text/javascript"> var performance = window.performance || window.msPerformance || window.webkitPerformance; if (performance) { console.log(performance); } </script> </body> </html>
Then in the browser will print the following performance The basic information is as follows :
As you can see above ,performance Contains three objects , Respectively memory、navigation、timing. among memory It's about memory ,navigation It means source related , That is to say, I jumped from that place .timing It's the critical time . Let's introduce the specific property values of this object .
performance.memory The meaning is to show the memory usage at the moment , As you can see from the picture above , The object has three properties , Respectively :
jsHeapSizeLimit The meaning of this attribute is : Memory size limit .
totalJSHeapSize Express Total memory size .
usedJSHeapSize Indicates the amount of memory available .
If usedJSHeapSize Greater than totalJSHeapSize Words , Then there will be a memory leak problem , Therefore, it is not allowed to exceed this value .
performance.navigation Meaning is the source information of the page , The object has 2 Attribute values , Namely :redirectCount and type.
redirectCount: The value means : If there is a redirect , The page comes through several redirects , The default is 0;
type: The meaning of this value indicates how the page is opened . The default is 0. It can be taken as 0、1、2、255.
0(TYPE_NAVIGATE): Indicates normal access to the page ( Non refresh 、 No redirection ).
1(TYPE_RELOAD): Said by window.location.reload Refresh the page . If I refresh the next page now , If you look at the value, it becomes 1 了 .
2(TYPE_BACK_FORWARD ): Represents progress through the browser 、 Back button to enter the page . If I advance to the next page at this time , Back to the page , Check the printed value , Discovery becomes 2 了 .
255(TYPE_RESERVED): It means not entering the page in the above way .
As shown in the figure below :
performance.onresourcetimingbufferfull; The screenshot above also has this property , The meaning of this property is in a callback function . The callback function will execute when the browser's resource time performance buffer is full .
performance.timeOrigin: It's a series of time points , To the nearest millisecond . The value in the screenshot above is :1559526951495.139, The value is
A dynamic , Refresh , This value will change .
performance.timing: It's a series of key points in time , It contains the Internet 、 Analysis and so on a series of time data .
For convenience , I got a picture from the Internet , To analyze the meaning of each key time point as follows :
In the order shown above , Let's take a look at the meanings of each field as follows :
navigationStart: It means : Timestamp at the end of a page uninstall on the same browser . If there is no previous page , Then the value will go with fetchStart The value of is the same .
redirectStart: The meaning of this value is the first http Timestamp at the beginning of redirection , If there is no redirection , Or redirect to a different source , Then the value is returned as 0.
redirectEnd: the last one HTTP Timestamp when redirection is complete . If there is no redirection , Or redirect to a different source , The value is also returned as 0.
fetchStart: The browser is ready to use http The time when the document was requested ( Before checking the local cache ).
domainLookupStart: DNS Domain name query start time , If local caching is used , or Persistent links , This value is related to fetchStart Same value .
domainLookupEnd: DNS Time of domain name query completion , If local caching is used , or Persistent links , This value is related to fetchStart Same value .
connectStart: HTTP Time to start connection , If it's a persistent link , The value is the same as fetchStart Same value , If an error occurs at the transport layer and a connection needs to be reestablished , So here is the start time of the new link .
secureConnectionStart: HTTPS Connection start time , If it's not a secure connection , Then the value is 0
connectEnd:HTTP Time to complete connection ( Complete the handshake ). If it's a persistent link , The value is the same as fetchStart Same value , If an error occurs at the transport layer and a connection needs to be reestablished , So here is the new link completion time .
requestStart: http The time when the request to read the real document started , Including reading cache from local , When link error reconnects .
responseStart: Time to start receiving response ( When we get the first byte ). Including reading cache from local .
responseEnd: HTTP Time when the response is all received ( Get the last byte ). Including reading cache from local .
unloadEventStart: Previous page ( Same domain as current page )unload The timestamp , If there is no previous page or the previous page is a different domain , So the value is 0.
unloadEventEnd: and unloadEventStart Corresponding , Back to the previous page unload Time stamp of the completion of the callback function of event binding .
domLoading: Start parsing rendering DOM Tree time .
domInteractive: Finish parsing DOM Tree time ( It's just DOM Tree parsing complete , But it didn't start loading the web resources ).
domContentLoadedEventStart:DOM After parsing , Start time of loading resources in the web page .
domContentLoadedEventEnd: DOM After parsing , The time when the resources in the web page are loaded .
domComplete: DOM Tree parsing complete , And when the resources are ready .Document.readyState Turn into complete, And will throw readystatechange Related events .
loadEventStart: load Event sent to document . That is to say load When the callback function starts executing , If there is no binding load event , The value is 0.
loadEventEnd: load The time when the callback function of the event finished executing , If there is no binding load event , The value is 0.
Above is the meaning of each value , Let's have a brief look at , Just get to know , Don't worry too much . Use these values to calculate the white screen time 、 First screen time 、 User operable time nodes , The total download time of the page 、DNS The time of the query 、TCP Link time before , Let's first look at how the traditional scheme is done ?
Traditional scheme
In the API Before appearance , If we want to calculate the performance of the front-end above , We need to use time stamps to approximate how long it will take . For example, use :(new Date()).getTime() To calculate the values before and after , Then the difference between the two values is the time spent in this period . But there are errors in this method , inaccurate . Let's take a look at the traditional scheme as follows :
1.1 White screen time
White screen time : It means that the user enters the website ( For example, refresh the page 、 Jump to a new page etc. by this way ) Time to start counting , Until the time node before the content of the page is displayed . As we can see above , This process includes dns Inquire about 、 establish tcp link 、 Send the first http Request and so on 、 return html file .
For example, the following code :
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>performance demonstration </title> <script type="text/javascript"> var startTime = (new Date()).getTime(); </script> <link href="xx1.css" rel="stylesheet" /> <link href="xx2.css" rel="stylesheet" /> <script type="text/javascript" src="xx1.js"></script> <script type="text/javascript" src="xx2.js"></script> <script type="text/javascript"> var endTime = (new Date()).getTime(); </script> </head> <body> <script type="text/javascript">
</script>
</body>
</html>
Code above ,endTime - startTime The value of can be used as the estimation of white screen time .
1.2 First screen time
To get the calculation of the first screen time , First of all, we need to know that there are 2 Ways of planting :
1. After loading the resource file, pass js Get interface data dynamically , Then the data comes back to render the content .
So there will be an infographic like this : As shown below :
2. Isomorphism straight out front page , As shown below :
css Calculation of loading time of resource file , We can do this as shown above :t2-t1 It's all css Loading time .
So if our current project file code index.html The code is as follows :
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>performance demonstration </title>
<script type=“text/javascript”>
// Get the start time of the page
var pageStartTime = (new Date()).getTime();
</script>
<link href=“xx1.css” rel=“stylesheet” />
<link href=“xx2.css” rel=“stylesheet” />
<script type=“text/javascript”>
// Get... After loading css Time for
var cssEndTime = (new Date()).getTime();
</script>
<script type=“text/javascript” src=’./jquery.js’></script>
<script type=“text/javascript”>
// Get loaded jquery Plug in time
var jsPluginTime = (new Date()).getTime();
</script>
</head>
<body>
<h1> computing time </h1>
<script type=“text/javascript”>
// load js Start time of
var JsStartTime = (new Date()).getTime();
</script>
<script type=“text/javascript” src=“xx1.js”></script>
<script type=“text/javascript” src=“xx2.js”></script>
<script type=“text/javascript”>
// After loading js The end time of
var JsEndTime = (new Date()).getTime();
</script>
</body>
</html>
Code above , You can get the start time of the page pageStartTime, Load resource file css The time after that is cssEndTime - pageStartTime, load jquery Plug in time jsPluginTime - cssEndTime 了 . however js Is the load time of = JsEndTime - JsStartTime Do you ? It must not be , because JS There needs to be time to execute . such as js A lot has been done inside dom operation , that dom It takes time to operate , that js Loading and execution time = JsEndTime - JsStartTime; Do you ? It's also wrong , Because browsers load resource files in parallel , perform js Files are serial . Then if css File or jquery Document origination http Never returned after the request , Then it will block the follow-up js The execution of the document . But right now js The file load has been returned for a long time , But due to server or network reasons css File loading is slow , So it's clogging up js Execution of documents .
So we can sum it up as :js Loading time It's not equal to JsEndTime - JsStartTime; Empathy js The actual loading and execution Also is not equal to JsEndTime - JsStartTime. Because of the chain css Medium http request , It will clog js Implementation , So a lot of websites will link out css File changed to inline css File code , inline css The code is serial . For example, Baidu. , Taobao official website, etc . Let's take a look at the source code of these two websites :
Baidu source :
We open Baidu search page , Then we right-click to see the source code of the web page as follows :
Let's take a look at the Internet of Baidu search page css The request for is as follows , There is no such thing as css Chain operation , be-all css The code is all inline , When we check the Internet, we can see that there is only one css Outer chain request , And it's time to css It's not inside Baidu css file , As shown below :
Taobao official website source code :
We operate as shown above , Open Taobao official source code to see the following :
And we see only two requests from Taobao official website css Outer chain request , And the two outer chain requests are not under the same domain name in Taobao css request ,
As shown below :
also The css The file named new_suggest-min.css file , I search through the source code , I didn't find out css Document chain , So it is certain that css The document is passed js Dynamically loaded , As shown below :
Bear in mind : If body There are more than one js Word of the file , And there are ajax Dynamic rendering of the file , Then try to put him at the front , Because of the others js Loading will prevent the rendering of the page , Causes rendering js It can't be played up all the time , The data of the page will be blank for a period of time .
Two : Use performance.timing To calculate the value
performance The object has a timing attribute , This property contains many property values , Let's take a look at the diagram before , As shown below :
From the diagram above we can see :
Redirection takes time = redirectEnd - redirectStart; DNS Query time consuming = domainLookupEnd - domainLookupStart; TCP Link time consuming = connectEnd - connectStart; HTTP The request takes time = responseEnd - responseStart; analysis dom Trees take time = domComplete - domInteractive; White screen time = responseStart - navigationStart; DOMready Time = domContentLoadedEventEnd - navigationStart; onload Time = loadEventEnd - navigationStart;
That's how it's calculated , For convenience we can now encapsulate them as a function , Then calculate the corresponding value , Then we can optimize according to the corresponding data value .
Let's wrap this up js Calculation method of , The code is as follows :
function getPerformanceTiming() { var performance = window.performance; if (!performance) { console.log(' Your browser does not support it performance attribute '); return; } var t = performance.timing; var obj = { timing: performance.timing }; // Redirection takes time obj.redirectTime = t.redirectEnd - t.redirectStart;
// DNS Query time consuming
obj.lookupDomainTime = t.domainLookupEnd - t.domainLookupStart;
// TCP Link time consuming
obj.connectTime = t.connectEnd - t.connectStart;
// HTTP The request takes time
obj.requestTime = t.responseEnd - t.responseStart;
// analysis dom Trees take time
obj.domReadyTime = t.domComplete - t.domInteractive;
// White screen time consuming
obj.whiteTime = t.responseStart - t.navigationStart;
// DOMready Time
obj.domLoadTime = t.domContentLoadedEventEnd - t.navigationStart;
// Page load time namely :onload Time
obj.loadTime = t.loadEventEnd - t.navigationStart;
return obj;
}
var obj = getPerformanceTiming();
console.log(obj);
3、 ... and : How to optimize the front-end performance ?
1. In the web page ,css Try to inline resource files , Don't chain , The specific reasons are explained above .
2. Redirect optimization , Redirection has 301( Permanent redirection )、302( Temporary redirection )、304(Not Modified). The first two kinds of redirection should be avoided as much as possible .304 It's for caching . Redirection takes time .
3. DNS Optimize , How do you optimize it ? There are generally two points : The first is to reduce DNS Number of requests , The second is to carry on DNS Pre acquisition of (Prefetching). stay PC End normal parsing DNS It costs... At a time 20-120 Time in milliseconds . So we can reduce DNS Number of parsing , And then there will be less DNS Time of resolution .
The second one is DNS Pre acquisition of , What is pre acquisition ?DNS Prefetching is when the browser attempts to resolve the domain name before the user accesses the link . For example, there are many links in our website , But these links are not under the same domain name , We can resolve the domain name when the browser loads , When the user actually clicks the pre parsed link , Can be reduced on average 200 Time in milliseconds ( The first time you visit the domain name , Without caching ). This can reduce the waiting time of users , Improve user experience .
We can see the code of Taobao's official website as follows DNS Of Prefetch 了 , As shown below :
DNS Prefetch You should try to put it in front of the page , It's recommended to put it in <meta charset="UTF-8"> Back . The specific use method is as follows :
<link rel="dns-prefetch" href="//xxx.abc.com"> <link rel="dns-prefetch" href="//yyy.def.com"> <link rel="dns-prefetch" href="//bdimg.share.zhix.net">
4. TCP Request to optimize
TCP Optimization is to reduce HTTP The number of requests . For example, front-end resource merging , picture , Resource file compression and so on .
stay http1.0 Short links are used by default , That is to say, the client and the server will have one session http On request , A link will be created , The link will be broken at the end of the task . Then there will be 3 Time TCP Ask for a handshake and 4 Time TCP Request release operation .
stay http1.1 in , stay http The response header will add Connection: keep-alive, The meaning of the code is : When the page is finished , The link will not be closed immediately ,
When we visit the link again , Will continue to use this long connection . This reduces TCP The number of handshakes and releases . It only needs to be established once TCP Link to , For example, let's look at Baidu's request as follows :
5. Rendering optimization
Before we do vue or react Project time , Our common template page is through js To render . Instead of isomorphism html page , For this rendering process, there will be a great loss for our first screen , White screen time will increase . So we can use isomorphic direct out to render on the server side html The page will be better , Or we can use some webpack Tool execution html Isomorphic rendering ,webpack Rendering can see This article .
Four :Performance Medium method
First, we print it in the console performance What are the ways of , The following code :
var performance = window.performance; console.log(performance);
As shown below :
4.1 performance.getEntries()
This method contains an array list of all static resources .
For example, I am now html The code is as follows :
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>performance demonstration </title> </head> <body> <h1> computing time </h1> <img src="http://img.alicdn.com/tps/TB1EMhjIpXXXXaPXVXXXXXXXXXX.jpg" /> <script type="text/javascript"> window.onload = function() { var performance = window.performance; console.log(performance); console.log(performance.getEntries()) } </script> </body> </html>
Code above , My page contains a Taobao cdn The picture above , Because this method will get all the HTTP request .
Then we see printing in the browser performance.getEntries() The information is as follows :
The object's properties include the resource load time , There are several common properties as follows :
name: Resource name , It's the absolute path of resources , This is Taobao cdn The path of the picture above . We can go through performance.getEntriesByName(name Property value ), To get the specific properties of the resource load .
startTime: Starting time
duration: Indicates the load time , It's a millisecond number , Only time points in the same domain can be obtained , If it's cross domain , Then the time is 0.
entryType: The resource type "resource", also "navigation", "mark" and "measure" These three .
initiatorType: A label indicating the source of the request , such as link label 、script label 、img Labels etc. .
So we can look like getPerformanceTiming The method is the same , Encapsulate a method , Time to acquire a resource . Here's how to encapsulate the code :
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>performance demonstration </title> </head> <body> <h1> computing time </h1> <img src="http://img.alicdn.com/tps/TB1EMhjIpXXXXaPXVXXXXXXXXXX.jpg" /> <script type="text/javascript"> // Calculate load time function getEntryTiming (entry) { var obj = {}; // Get redirection time obj.redirectTime = entry.redirectEnd - entry.redirectStart; // obtain DNS Query time consuming obj.lookupDomainTime = entry.domainLookupEnd - entry.domainLookupStart; // obtain TCP Link time consuming obj.connectTime = entry.connectEnd - entry.connectStart; // HTTP The request takes time obj.requestTime = entry.responseEnd - entry.responseStart;obj.name </span><span style="background-color: rgba(245, 245, 245, 1); color: rgba(0, 0, 0, 1)">=</span><span style="background-color: rgba(245, 245, 245, 1); color: rgba(0, 0, 0, 1)"> entry.name; obj.entryType </span><span style="background-color: rgba(245, 245, 245, 1); color: rgba(0, 0, 0, 1)">=</span><span style="background-color: rgba(245, 245, 245, 1); color: rgba(0, 0, 0, 1)"> entry.entryType; obj.initiatorType </span><span style="background-color: rgba(245, 245, 245, 1); color: rgba(0, 0, 0, 1)">=</span><span style="background-color: rgba(245, 245, 245, 1); color: rgba(0, 0, 0, 1)"> entry.initiatorType; obj.duration </span><span style="background-color: rgba(245, 245, 245, 1); color: rgba(0, 0, 0, 1)">=</span><span style="background-color: rgba(245, 245, 245, 1); color: rgba(0, 0, 0, 1)"> entry.duration; </span><span style="background-color: rgba(245, 245, 245, 1); color: rgba(0, 0, 255, 1)">return</span><span style="background-color: rgba(245, 245, 245, 1); color: rgba(0, 0, 0, 1)"> obj; } window.onload </span><span style="background-color: rgba(245, 245, 245, 1); color: rgba(0, 0, 0, 1)">=</span> <span style="background-color: rgba(245, 245, 245, 1); color: rgba(0, 0, 255, 1)">function</span><span style="background-color: rgba(245, 245, 245, 1); color: rgba(0, 0, 0, 1)">() { </span><span style="background-color: rgba(245, 245, 245, 1); color: rgba(0, 0, 255, 1)">var</span><span style="background-color: rgba(245, 245, 245, 1); color: rgba(0, 0, 0, 1)"> entries </span><span style="background-color: rgba(245, 245, 245, 1); color: rgba(0, 0, 0, 1)">=</span><span style="background-color: rgba(245, 245, 245, 1); color: rgba(0, 0, 0, 1)"> window.performance.getEntries(); console.log(entries); entries.forEach(</span><span style="background-color: rgba(245, 245, 245, 1); color: rgba(0, 0, 255, 1)">function</span><span style="background-color: rgba(245, 245, 245, 1); color: rgba(0, 0, 0, 1)">(item) { </span><span style="background-color: rgba(245, 245, 245, 1); color: rgba(0, 0, 255, 1)">if</span><span style="background-color: rgba(245, 245, 245, 1); color: rgba(0, 0, 0, 1)"> (item.initiatorType) { </span><span style="background-color: rgba(245, 245, 245, 1); color: rgba(0, 0, 255, 1)">var</span><span style="background-color: rgba(245, 245, 245, 1); color: rgba(0, 0, 0, 1)"> curItem </span><span style="background-color: rgba(245, 245, 245, 1); color: rgba(0, 0, 0, 1)">=</span><span style="background-color: rgba(245, 245, 245, 1); color: rgba(0, 0, 0, 1)"> getEntryTiming(item); console.log(curItem); } }); }
</script>
</body>
</html>
Then there will be 2 individual console.log Print data , We see the print information in the console as follows :
As shown in the figure above , We can see through getEntryTiming Method after calculation , I will get the corresponding values .
4.2 performance.now()
This method will return a timestamp of the execution time of the current page , Can be used to accurately calculate the actual execution of the program .
Such as the following , I cycle 100 Ten thousand times , Then return an array , Let's look at the code as follows :
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>performance demonstration </title> </head> <body> <h1> computing time </h1> <img src="http://img.alicdn.com/tps/TB1EMhjIpXXXXaPXVXXXXXXXXXX.jpg" /> <script type="text/javascript"> function doFunc() { var arrs = []; for (var i = 0; i < 1000000; i++) { arrs.push({ 'label': i, 'value': i }); } return arrs; } var t1 = window.performance.now(); console.log(t1); doFunc(); var t2 = window.performance.now(); console.log(t2); console.log('doFunc Function executed at :'+ (t2 - t1) + ' millisecond '); </script> </body> </html>
Then we'll print doFunc() How long did this function last , As shown below :
We also know that we have another time Date.now(), however performance.now() And Date.now() The difference is :
This method uses a floating-point number , Returned in milliseconds , Decimal point accurate to the delicate level of time . be relative to Date.now() More precise , And will not be affected by system program blocking .
Let's take a look at using Date.now() Method used demo as follows :
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>performance demonstration </title> </head> <body> <h1> computing time </h1> <img src="http://img.alicdn.com/tps/TB1EMhjIpXXXXaPXVXXXXXXXXXX.jpg" /> <script type="text/javascript"> function doFunc() { var arrs = []; for (var i = 0; i < 1000000; i++) { arrs.push({ 'label': i, 'value': i }); } return arrs; } var t1 = Date.now(); console.log(t1); doFunc(); var t2 = Date.now(); console.log(t2); console.log('doFunc Function executed at :'+ (t2 - t1) + ' millisecond '); </script> </body> </html>
The results of the implementation are as follows :
Be careful :performance.timing.navigationStart + performance.now() About equal to Date.now();
4.3 performance.mark()
The meaning of this method is to customize the time when the tag is added , It is convenient for us to calculate the running time of the program . The method is used as follows :
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>performance demonstration </title> </head> <body> <h1> computing time </h1> <img src="http://img.alicdn.com/tps/TB1EMhjIpXXXXaPXVXXXXXXXXXX.jpg" /> <script type="text/javascript"> function doFunc() { var arrs = []; for (var i = 0; i < 1000000; i++) { arrs.push({ 'label': i, 'value': i }); } return arrs; } // Make a mark before function execution var mStart = 'mStart'; var mEnd = 'mEnd'; window.performance.mark(mStart); doFunc(); // After the function is executed, make a mark window.performance.mark(mEnd); // Then measure the distance between the two marks , And save it var name = 'myMeasure'; window.performance.measure(name, mStart, mEnd); // So let's go through performance.getEntriesByName Method to get the value console.log(performance.getEntriesByName('myMeasure')); console.log(performance.getEntriesByType('measure')); </script> </body> </html>
Code above , We go through window.performance.measure(name, mStart, mEnd); After this method is marked , We can use performance.getEntriesByName('myMeasure') and performance.getEntriesByType('measure') Get the value .
As shown in the figure below :
4.4 performance.getEntriesByType()
This method returns a PerformanceEntry List of objects , Based on a given entry type, Code above performance.getEntriesByType('measure') You can get the value .
4.5 performance.clearMeasures()
Remove the custom added... From the browser's performance input buffer measure. The code is as follows :
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>performance demonstration </title> </head> <body> <h1> computing time </h1> <img src="http://img.alicdn.com/tps/TB1EMhjIpXXXXaPXVXXXXXXXXXX.jpg" /> <script type="text/javascript"> function doFunc() { var arrs = []; for (var i = 0; i < 1000000; i++) { arrs.push({ 'label': i, 'value': i }); } return arrs; } // Make a mark before function execution var mStart = 'mStart'; var mEnd = 'mEnd'; window.performance.mark(mStart); doFunc(); // After the function is executed, make a mark window.performance.mark(mEnd); // Then measure the distance between the two marks , And save it var name = 'myMeasure'; window.performance.measure(name, mStart, mEnd); // So let's go through performance.getEntriesByName Method to get the value console.log(performance.getEntriesByName('myMeasure')); console.log(performance.getEntriesByType('measure'));</span><span style="background-color: rgba(245, 245, 245, 1); color: rgba(0, 128, 0, 1)">//</span><span style="background-color: rgba(245, 245, 245, 1); color: rgba(0, 128, 0, 1)"> Use performance.clearMeasures() Method to clear Custom added measure</span>
performance.clearMeasures();
console.log(performance.getEntriesByType(‘measure’));
</script>
</body>
</html>
As above we use in the final code performance.clearMeasures() Method clears all custom measure. And then we use it again later console.log(performance.getEntriesByType('measure')); Print , See the following information :
4.6 performance.getEntriesByName(name The value of the property )
This method returns a PerformanceEntry List of objects , Based on a given name and entry type.
4.7 performance.toJSON()
The method is a JSON Format converter , return Performance Object's JSON object . As shown in the following code :
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>performance demonstration </title> </head> <body> <h1> computing time </h1> <img src="http://img.alicdn.com/tps/TB1EMhjIpXXXXaPXVXXXXXXXXXX.jpg" /> <script type="text/javascript"> console.log(window.performance); var js = window.performance.toJSON(); console.log("json = " + JSON.stringify(js)); </script> </body> </html>
Then print the information as follows :
5、 ... and : Use performane Write gadgets
First html The usage code is as follows ( Remember to put the initial code in window.onload Inside , Because make sure the image is loaded ):
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>performance demonstration </title> </head> <body> <h1> computing time </h1> <img src="http://img.alicdn.com/tps/TB1EMhjIpXXXXaPXVXXXXXXXXXX.jpg" /> <img src="https://aecpm.alicdn.com/simba/img/TB1XotJXQfb_uJkSnhJSuvdDVXa.jpg" /> <script type="text/javascript" src="./js/performance.js"></script> <script type="text/javascript"> window.onload = function() { window.performanceTool.getPerformanceTiming(); }; </script> </body> </html>
Then preview the page as follows :
As shown in the picture above, we can see clearly , The basic information of the page , such as : Redirection takes time 、Appcache Time consuming 、DNS Query time consuming 、TCP Link time consuming 、HTTP The request takes time 、 The request is over DOM Loading time 、 analysis DOM Trees take time 、 White screen time consuming 、load The event took time 、 And Page load time . Page load time It's the sum of all the time above . And below , We can also see clearly ,js、css、image、video、 How long does it take to load the information resources .
js The basic code is as follows :
src/utils.js The code is as follows :
export function isObject(obj) { return obj !== null && (typeof obj === 'object') }
// Format in milliseconds
export function formatMs(time) {
if (typeof time !== ‘number’) {
console.log(‘ Time must be a number ’);
return;
}
// Millisecond to second return
if (time > 1000) {
return (time / 1000).toFixed(2) + ‘s’;
}
// Default return milliseconds
return Math.round(time) + ‘ms’;
}
export function isImg(param){
if (/.(gif|jpg|jpeg|png|webp|svg)/i.test(param)) {
return true;
}
return false;
}
export function isJS(param){
if (/.(js)/i.test(param)) {
return true;
}
return false;
}
export function isCss(param){
if (/.(css)/i.test(param)) {
return true;
}
return false;
}
export function isVideo(param){
if (/.(mp4|rm|rmvb|mkv|avi|flv|ogv|webm)/i.test(name)) {
return true;
}
return false;
}
export function checkResourceType(param){
if (isImg(param)) {
return ‘image’;
}
if (isJS(param)) {
return ‘javascript’;
}
if (isCss(param)) {
return ‘css’;
}
if (isVideo(param)) {
return ‘video’;
}
return ‘other’
}
js/index.js The code is as follows :
var utils = require('./utils'); var formatMs = utils.formatMs; var isObject = utils.isObject; var checkResourceType = utils.checkResourceType;
function Performance() {};
Performance.prototype = {
// Get data information
getPerformanceTiming: function() {
// Initialization data
this.init();
if (!isObject(this.timing)) {
console.log(‘ Value needs to be an object type ’);
return;
}
// Early acquisition loadEventEnd The value would be 0
var loadTime = this.timing.loadEventEnd - this.timing.navigationStart;
if (loadTime < 0) {
setTimeout(() => {
this.getPerformanceTiming();
}, 200);
return;
}
// Get the parsed data
this.afterDatas.timingFormat = this._setTiming(loadTime);
this.afterDatas.enteriesResouceDataFormat = this._setEnteries();
this._show();
},
init: function() {
this.timing = window.performance.timing;
// The type of access resource is resource All data for
this.enteriesResouceData = window.performance.getEntriesByType(‘resource’);
},
// Save original data
timing: {},
// original enteries data
enteriesResouceData: [],
// Save the parsed data
afterDatas: {
timingFormat: {},
enteriesResouceDataFormat: {},
enteriesResouceDataTiming: {
“js”: 0,
“css”: 0,
“image”: 0,
“video”: 0,
“others”: 0
}
},
_setTiming: function(loadTime) {
var timing = this.timing;
// Calculate the data
var data = {
“ Redirection takes time ”: formatMs(timing.redirectEnd - timing.redirectStart),
“Appcache Time consuming ”: formatMs(timing.domainLookupStart - timing.fetchStart),
“DNS Query time consuming ”: formatMs(timing.domainLookupEnd - timing.domainLookupStart),
“TCP Link time consuming ”: formatMs(timing.connectEnd - timing.connectStart),
“HTTP The request takes time ”: formatMs(timing.responseEnd - timing.responseStart),
“ The request is over DOM Loading time ”: formatMs(timing.domInteractive - timing.responseEnd),
“ analysis DOM Trees take time ”: formatMs(timing.domComplete - timing.domInteractive),
“ White screen time consuming ”: formatMs(timing.responseStart - timing.navigationStart),
“load The event took time ”: formatMs(timing.loadEventEnd - timing.loadEventStart),
“ Page load time ”: formatMs(loadTime)
};
return data;
},
_setEnteries: function() {
var enteriesResouceData = this.enteriesResouceData;
var imageArrs = [],
jsArrs = [],
cssArrs = [],
videoArrs = [],
otherArrs = [];
enteriesResouceData.map(item => {
var d = {
‘ Resource name ’: item.name,
‘HTTP Protocol type ’ : item.nextHopProtocol,
“TCP Link time consuming ” : formatMs(item.connectEnd - item.connectStart),
“ Loading time ” : formatMs(item.duration)
};
switch(checkResourceType(item.name)) {
case ‘image’:
this.afterDatas.enteriesResouceDataTiming.image += item.duration;
imageArrs.push(d);
break;
case ‘javascript’:
this.afterDatas.enteriesResouceDataTiming.js += item.duration;
jsArrs.push(d);
break;
case ‘css’:
this.afterDatas.enteriesResouceDataTiming.css += item.duration;
cssArrs.push(d);
break;
case ‘video’:
this.afterDatas.enteriesResouceDataTiming.video += item.duration;
videoArrs.push(d);
break;
case ‘others’:
this.afterDatas.enteriesResouceDataTiming.others += item.duration;
otherArrs.push(d);
break;
}
});
return {
‘js’: jsArrs,
‘css’: cssArrs,
‘image’: imageArrs,
‘video’: videoArrs,
‘others’: otherArrs
}
},
_show: function() {
console.table(this.afterDatas.timingFormat);
for( var key in this.afterDatas.enteriesResouceDataFormat ){
console.group(key + “— Total load time ” + formatMs(this.afterDatas.enteriesResouceDataTiming[key]));
console.table(this.afterDatas.enteriesResouceDataFormat[key]);
console.groupEnd(key);
}
}
};
var Per = new Performance();
module.exports = Per;
Be careful : hold github After downloading the source code , need perform npm run build pack , After packing , hold dist/ Under the js Copy the file to your project , Then introduce the js file , Then you can see some information effects in the console .
notes : The basic code also refers to github On some code . It doesn't matter , It's important to learn , And can be used in projects . Increase of efficiency .
<div class="clear"></div>
<div id="post_next_prev">
<a href="https://www.cnblogs.com/tugenhua0707/p/10945934.html" class="p_n_p_prefix">« </a> Last one : <a href="https://www.cnblogs.com/tugenhua0707/p/10945934.html" title=" Published on 2019-05-29 20:17">nginx Turn on HSTS Let the browser force a jump HTTPS visit </a>
<br>
<a href="https://www.cnblogs.com/tugenhua0707/p/10991363.html" class="p_n_p_prefix">» </a> Next : <a href="https://www.cnblogs.com/tugenhua0707/p/10991363.html" title=" Published on 2019-06-08 18:49"> understand serverless No service architecture principle ( One )</a>
- classification Performance related
- label Performance --- Front end performance monitoring
· understand ASP.NET Core - Host
· Ingenious use background Achieve fancy text effect
· Go Concurrent programming – Use... Correctly goroutine
· Front end tile map loading legend of Zelda, breath of the wilderness
· Advanced technology management —— About cost optimization and benefit distribution mechanismLatest news :
· What's the change in the body after astronauts go home , Some key points you may want to know (2021-09-18 14:00)
· Price reduction due to increase ,iPhone13 The series sold out in a few seconds , The domestic high-end machine market may accelerate the reshuffle (2021-09-18 13:48)
· Iron Starbucks , The new drink of running water (2021-09-18 13:35)
· Lay time for crystal discovery , harvard 、 Stanford 、 East University 、UCB The researcher received 2022 New Vision Award !(2021-09-18 13:20)
· 2021 AI The sprint time of the track (2021-09-18 13:08)
» More news ...</div> <script type="text/javascript"> var m = window.__blog.contentRendered; if (m) { m(__$("content")); } </script> <div id="sidebar"> <div id="about"> <div> <h2 id="about_title">About</h2> <div id="about_body"> <div id="sidebar_news">
: Zhejiang - Hangzhou
Tu Genhua
t879083421
: Front end siege Division
:web front end 、 Travel, etc .
: What a long long road! I will go up and down ~~
It can be understood as 2 Key words : Fine and easy , Detailed details , Try to ensure that each article is very detailed , Easy easy , And ensure that each article is more understandable , Easier to understand thoroughly , A deeper understanding . Whether you are a front-end bull , Or front-end Xiaobai who wants to learn this knowledge point , All hope to understand and understand ~
Do the most professional blog , Share more knowledge ~ For everyone to study together ~ Share together ~Alibaba's philosophy is : Let the world have no difficult business , My current company ( Tongban Street ) The idea is : Make money more valuable , My idea of writing this article : Be the most professional blog in the world . The difference between Taobao and other industries is : Many kinds , The price is relatively cheap , The difference between jd.com and jd.com is : Logistics is fast , The goods are more authentic . The difference between pinduoduo is : Very cheap . The difference between our company is : Fast payment , There are many kinds of financial management , Very smart . And I have defined two keywords : Easy and fine , Easy and detailed , Try to ensure that each article is very detailed and easy to understand , This is the purpose that I have been studying and writing articles recently .The latest essay
- understand RESTful API design code
- understand Unicode code
- understand Javascript Execution process
- Jenkins Realize front-end automatic packaging , Automatically deploy code and email reminder function
- Front end workflow specification
- vue series ---Mustache.js Template engine introduction and source code analysis ( Ten )
- vue series ---snabbdom.js Use and source code analysis ( Nine )
- vue series ---Vue Implementation principle of componentization ( 8、 ... and )
- vue series --- know Flow( One )
- vue series --- understand Vue Medium computed,watch,methods The difference and source code implementation ( 6、 ... and )
Essay files
- 2020 year 1 month (1)
- 2019 year 12 month (2)
- 2019 year 11 month (2)
- 2019 year 10 month (10)
- 2019 year 8 month (10)
- 2019 year 7 month (12)
- 2019 year 6 month (9)
- 2019 year 5 month (11)
- 2019 year 4 month (17)
- 2019 year 3 month (6)
- 2019 year 2 month (1)
- 2019 year 1 month (9)
- 2018 year 12 month (4)
- 2018 year 11 month (9)
- 2018 year 10 month (10)
- 2018 year 9 month (8)
- 2018 year 8 month (10)
- 2018 year 7 month (9)
- 2018 year 6 month (10)
- 2018 year 5 month (5)
- 2018 year 4 month (9)
- 2018 year 3 month (7)
- 2018 year 2 month (3)
- 2018 year 1 month (5)
- 2017 year 12 month (9)
- 2017 year 11 month (1)
- 2017 year 10 month (5)
- 2017 year 9 month (9)
- 2017 year 8 month (10)
- 2017 year 7 month (3)
- 2017 year 6 month (2)
- 2017 year 5 month (11)
- 2017 year 4 month (2)
- 2016 year 6 month (3)
- 2016 year 5 month (2)
- 2016 year 4 month (2)
- 2016 year 3 month (3)
- 2016 year 2 month (3)
- 2016 year 1 month (2)
- 2015 year 12 month (4)
- 2015 year 11 month (1)
- 2015 year 10 month (1)
- 2015 year 9 month (3)
- 2015 year 8 month (5)
- 2015 year 7 month (9)
- 2015 year 6 month (6)
- 2015 year 5 month (11)
- 2015 year 4 month (9)
- 2015 year 3 month (8)
- 2015 year 2 month (2)
- 2015 year 1 month (2)
- 2014 year 12 month (4)
- 2014 year 11 month (6)
- 2014 year 10 month (2)
- 2014 year 9 month (5)
- 2014 year 8 month (3)
- 2014 year 7 month (6)
- 2014 year 6 month (5)
- 2014 year 5 month (3)
- 2014 year 4 month (5)
- 2014 year 3 month (2)
- 2014 year 2 month (2)
- 2014 year 1 month (13)
- 2013 year 12 month (14)
- 2013 year 11 month (7)
- 2013 year 10 month (5)
- 2013 year 9 month (2)
- 2013 year 8 month (10)
- more
Article archives
Points and rankings
- integral - 955793
- ranking - 256
Essay classification
- CSS(9)
- CSS3(14)
- Ecmascript 6(3)
- egg(3)
- Electron dependent (6)
- ES6(10)
- HTML(1)
- HTML5(25)
- javascript(110)
- javascript Understanding of design patterns (4)
- javascript Data structure and algorithm (9)
- javascript Regular expressions (2)
- JS The underlying knowledge (2)
- koa2(7)
- Mongodb(13)
- mysql(9)
- nginx dependent (9)
- nodeJS(21)
- PM2(1)
- ReactJS(3)
- Redis(3)
- requireJS(2)
- RESTful API design code (1)
- Serverless(3)
- service worker(7)
- SSR Server-side rendering (1)
- SVG(3)
- vue(21)
- web workers(1)
- webpack(27)
- websocket(7)
- web Safety related (4)
- Cache related (2)
- Front end test framework (2)
- Front end workflow specification (2)
- Front end project tools (28)
- thorough Vue Technology stack and source code series (10)
- Performance related (1)
- Source code analysis (9)
Reading the leaderboard
- 1. JS Date format conversion method (401425)
- 2. understand CSS3 Medium background-size( Scale the responsive image equally )(165982)
- 3. understand Vue Medium Render Rendering function (123498)
- 4. understand webpack And process.env.NODE_ENV Detailed explanation ( eighteen )(120926)
- 5. POST Submission of data ---Content-Type The understanding of the ;(109052)
- 6. Git Use the tutorial (99508)
- 7. Javascript Detailed explanation of design mode (82047)
- 8. understand WebSocket Heartbeat and reconnection mechanism ( 5、 ... and )(81526)
- 9. understand Vuex Auxiliary function of mapState, mapActions, mapMutations usage (80033)
- 10. MongoDB Visualization tools --Robo 3T Use the tutorial (78783)
- 11. understand vue Medium scope Use (73200)
- 12. css3 Realize equal scale enlargement and reduction of pictures (70630)
- 13. 30 I'll teach you by hand webpack actual combat (69875)
- 14. web Safety XSS Attack principle and prevention (69382)
- 15. Nginx Medium Rewrite Redirection configuration and practice of (67557)
- 16. HTTP In request request payload and formData difference ?(65815)
- 17. Echarts Detailed explanation of histogram configuration (60211)
- 18. nodeJS- Use buffer Class handles binary data (48611)
- 19. scp Command to transfer files (47646)
- 20. javascript and HTML5 Preview the image before uploading (43272)
Copyright 2021 Longen 0707
Powered by .NET 6 on Kubernetes</div> </div>
边栏推荐
- 单片机入门知识
- SQL injection
- 设备重启卡死问题分析-reboot卡死
- Municipalités locales - importations, exportations et balance commerciale (2000 - 2020)
- 字节流
- 鼓励企业知识共享的好处,你知道多少?
- 上市公司环境数据集:环境绩效明细表、排放明细表、资源消耗明细表等多项指标数据
- Luoyang comprehensive bonded zone was officially approved by the State Council to be established
- String class
- 力扣题之回文数
猜你喜欢
随机推荐
[原创]一种自动化九点标定工具原理(包涵部分源码)
FAQ during using Harry (question answering)
Nchw converted to nhwc
队列(堆栈)
uni拦截器
1978-2021中国统计年鉴、2003-2019(省、市面板数据)、1999-2019(县域面板数据)
Exception class
(1) Principle analysis of Tiktok Kwai short video watermarking
hdparm
Docker series VI Docker installation redis
Analysis of copyonwritearraylist
Handler学习
高频leetcode深搜部分:98. 验证二叉搜索树
High frequency leetcode deep search part: 617 Merge binary tree
文献: Axure(简单介绍)
粘性定位(sticky)详解
高频leetcode深搜部分:695. 岛屿的最大面积
High frequency leetcode deep search part: 98 Validate binary search tree
如何快速开发一个简单实用的MES系统?
High frequency leetcode deep search part: 297 Serialization and deserialization of binary tree
【 recommend 】 Cross platform configuration \ Industrial control \ Simulation \CAD 50 Line ten thousand C++ Full open source, free download !
【 recommend 】 Alibaba cloud Ambassador special offer : New users buy ECS The server 1 nucleus 2G The lowest price 87 element / year
【 recommend 】 With developers : Huawei developer community , Enter the technology brand zone of the blog Park
【 Extension 】 Yuanzi cooperates with aika automobile Aibao Insurance , You can buy a million dollar medical insurance at will