Li Huaxi, front-end development engineer of Weichi Cloud service team, likes to mess around, typical cat owner

The Console panel

This chapter please open devtools console/console. HTML

On the one hand, it is used to record information about the execution of the page (usually through various console statements), and on the other hand it is used as a shell window to execute scripts and interact with page documents, DevTools, and so on

Windows: Control + Shift + J Mac: Command + Option + J

First take a look at the methods under the console object:

console.clear()

As the name suggests, clear the console

console.log(), info(), warn(), error()

There is a small circle with a blue background in front of the output content of info, which is probably similar to this: I, then the Chrome update disappeared (IE can still see the difference)

Console. log(' general information ') console.info(' informative information ') console.error(' error information ') console.warn(' warning information ') Copy codeCopy the code

Use placeholders

Console. log(1, '2', +'3') // %s console.log(' tonight %s tiger ', 'hit ','?? ') / / % c console. The log (' % s % c tonight tigers', 'a', 'color: red,'????? ') // The configuration parameter copy code after the parameter with the placeholder belongs to the placeholderCopy the code

The rest of the list of placeholders is:

A placeholder function
%s string
%d The integer
%i The integer
%f Floating point Numbers
%o Links to objects
%c CSS Format string

console.time(), timeEnd()

Time and timeEnd are usually used together, and a parameter is passed to identify the starting position for the statistics:

console.time('t') Array(900000).fill({}).forEach((v, index) => v.index = index) console.timeEnd('t') // t: 28.18603515625ms Copy codeCopy the code

The execution time of the intermediate code is printed

console.count()

As the name suggests… Count, which can be used to count the number of times a function has been executed, or you can pass an argument and group the number of calls based on the passed argument

function foo(type = '') { type ? Console. count(type) : console.count() return 'type: '+ type} foo('A') //A: 1 foo('B') //B: 1 foo() 1 foo() //default: 2 foo() //default: 3 foo('A') //A: 2 Copy codeCopy the code

console.trace()

The call stack used to trace the code, without having to look at the breakpoint

Console.trace () function foo() {console.trace()} foo() copy the codeCopy the code

console.table()

The console.table() method converts data of a complex type into a table for display

Var arr = [{name: 'Messi ', qq: 10}, {name:' Cristiano ronaldo ', QQ: 7}, {name: 'Neymar ', qq: 11},] console.table(arrCopy the code

console.dir()

Prints objects in a form that is easy to read and print

Var obj = {name: 'justwe7', age: 26, fn: function () {alert('justwe7')},} console.log(obj) console.dir(objCopy the code

Print DOM objects:

console.assert()

Assertion, used to make conditional judgments. When the expression is false, an error message is displayed without interrupting program execution.

Can be used to alert the user that the internal state is not correct (catch the liar)

Var val = 1 console.assert(val === 1, '= 1') console.assert(val! == 1, 'not equal to 1') console.log(' code to go down ') copy the codeCopy the code

console.group(), groupEnd()

Output information in groups that can be folded/expanded with the mouse

Group (' group 1') console.log(' group 1-1111') console.log(' group 1-2222') console.log(' Group 1-3333') console.groupend () Group (' group 2') console.log(' Group 2-1111') console.log(' Group 2-2222') console.log(' Group 2-3333') console.groupEnd() Copy codeCopy the code

$The selector

The $_

The result of the last calculation can be recorded and used directly for code execution:

$0, $1... $4

Select a DOM node from the last 5 review elements. Select a DOM node from the last 5 review elements.

$and?

  • $(selector)Is an encapsulation of the native Document.querySelector ().
  • ? (selector)Returns all meet the selection criteria of the elements of a collection, is the document querySelectorAll () encapsulation

$x

Returns the matched nodes in an array

< ul > < ul > < li > < p > under the li of p1 < / p > < / li > < li > < p > under the li of p2 < / p > < / li > < li > < p > under the li of p3 < / p > < / li > < / ul > < / ul > < p > p < / p > duplicate code outsideCopy the code
$x (' / / li ') / / all li $x (' / / p) / / all p $x (' / / li / / p) / / all the li of p $x (' / / li [p] ') / / all li p copying codeCopy the code

keys(), values()

Same as the ES6 Object extension methods, object.keys () and object.values ()

keys(obj); values(obj); Copy the codeCopy the code

copy()

You can copy variables directly to the clipboard

Copy (temp1) Copies the codeCopy the code

Use artifact with Save Global variable

Element panel

This chapter please open devtools/element/element. The HTML

The Elements panel allows you to view all the page Elements in the form of a DOM tree, as well as to edit what you see is what you get

Windows: Control + Shift + C Mac: Command + Option + C

CSS debugging

style

Select the target node, Element panel, view style->: HOv, and select the corresponding state

computed

Sometimes styles are overwritten and cumbersome to look at, and computed comes in handy

Click on a style to jump directly to the CSS definition

Adjusts the value of an element

Select the value you want to change, press the arrow keys up or down to + / – 1 unit

Alt + arrow keys ×10 to adjust the unit value Ctrl + arrow keys ×100 to adjust the unit value Shift + arrow keys /10 to adjust the unit value

HTML debugging

SAO operation

Select the node, directly press the keyboard H to directly make the element show/hide, no need to manually tap the style, the effect is the same as visibility: hidden, or to occupy the space of the box model. (Remember to change the input method to English ~)

Stores an element in a global temporary variable

Select the node, right click, Store as global variable (also available in the Network panel, especially easy to filter interface return values)

Scroll to a node

If you have a long page and you want to find a position for a text node and you don’t want to Scroll through it manually, you can try Scroll into View

Edge’s exclusive 3D view

The USE of Chromium Edge is really a change of face, 3D view can help to locate some positioning levels and DOM nesting problems, the page structure is nice and intuitive to see (with the auxiliary function of the DOM tree is very comfortable to use)

This feature is currently not available in Chrome. Edge: Console open => Esc open drawer => select 3D View Panel

DOM breakpoint

You can listen to DOM node changes (child node changes/property changes/element removal) and break to the JS line that changed the DOM state:

The Network panel

You can view detailed information about resources requested over the network

Windows: Control + Shift + I Mac: Command + Option + I

According to the region, it can be roughly divided into the following areas:

  1. Controls – Control Network function options, as well as some display appearance

  2. Filters – Controls what types of resources are displayed in the Requests Table

    Tips: Hold Cmd (Mac) or Ctrl (Windows/Linux) and click filters to select more than one filter at a time

  3. Overview – This diagram shows a timeline of resource retrieval times. If you see multiple vertical bars stacked together, these resources are retrieved at the same time

  4. Requests Table – This Table lists each resource that was retrieved. By default, the table is sorted chronologically, with the oldest resource at the top. Click on the name of the resource to display more information. Tip: Right-click on any table title other than Timeline to add or remove information columns

  5. Summary – You can see at a glance the total number of requests for the page, the amount of data transferred, and the load time

(1, 2) Controls, Filters area

Displays of Filters control:

  • Use large request lines– By default,Requests TableA resource shows only a small line. The selectedUse large resource rowsThe (large resource line) button displays two text fields: primary and secondary.
  • Capture screen shot – When you hover over a screen shot, Timeline/Waterfall displays a vertical yellow line indicating when the frame was captured
  • Show Overview – Show the time taken for each phase of the page lifecycle (the Overview area) (the blue and green bars)

(3) Overview area

A summary of network resource loading time information for each phase of the page lifecycle. You can select regions to filter resource details for Requests tables

(4) Requests for Table area

The corresponding description of the title bar:

  • Name(name): Indicates the name of the resource.
  • Status(state): Indicates the HTTP status code.
  • Type(type): MIME type of the requested resource.
  • Initiator(a): The object or process that initiates the request. It may have the following values:
    • Parser(Parser): Chrome’s HTML parser initiates the request.
    • Redirect(Redirection): HTTP redirection starts the request.
    • Script(script): The script initiates the request.
    • Other(other): Some other process or action initiates a request, such as a user clicking a link to go to a page, or entering a url in the address bar.
  • Size(size): The size of the response header (usually several hundred bytes) plus the response data provided by the server.
  • Time(time): The total duration from the start of the request to the last byte in the received response
  • Timeline/Waterfall(Timeline): Displays visual statistics for all network requests

Right-click on a title bar such as (Name) to add or remove information columns. For example, you can add a Response Header => Content-encoding option to the list of gZIP compression of the page resources:

To initiatexhrrequest

The Network panel is probably what we use most when we connect with the back-end. But every time you want to review a request by refreshing the page, click the button and other ways to trigger the XHR request, this way sometimes seems more troublesome, you can Replay XHR way to initiate a new request:

View HTTP information

View the parameters of the network request

By clicking the View URL Encoded or View Decoded links next to Query String Parameters, View query String Parameters in the URL encoded or decoded format. This is especially useful when using Postman to copy related input parameters.

Click the Response TAB to view the unformatted HTTP Response for this resource

The return value of the interface (in Preview) works as wellSave global variableStore a global variable

Why do Size and Time have two lines of arguments?

About the Size column

Size has two lines:

  • The first row represents the dataWhen the transmissionAs shown in the figure above190KB
  • The second row represents the dataThe actualThe size of the708KB

On the server, gZIP compression algorithm is adopted to compress the original 708KB to 190KB, and the transmission size is shortened 3.7 times, which greatly improves the efficiency of resource transmission

Points to note:

Gzip compression compresses only the content of the response body, so it is suitable for large amounts of data to be returned. If the amount of data is too small, it may cause the data to be transferred larger than the actual size (adding some additional response headers).

About the Time

Time has two lines:

  • The first line represents the total time it takes from the time the client sends the request to the time the server returns all the data471ms
  • The second line represents the time from the time the client sends the request to the time the server returns the first byte, in the case of the figure above55ms

The time in the first line represents all items: resolving DNS, establishing a connection, waiting for the server to return data, transferring data, etc

The second line of time is the total time – the time the data was transferred

From the above analysis we can see that it took 55ms from the client request to the server when it was ready to return the data, but it took 471ms to transfer the data

This can take longer for users with slow networks, so keep the amount of data returned to a minimum when writing the code (interface)

Waterfall

Clicking on a resource will show detailed network loading information:

Related fields:

  • Queuing

    Browsers queue requests in the following situations

    1. There are higher priority requests that are deferred by the rendering engine, which often happens with images because it is considered lower priority than critical resources such as scripts/styles.
    2. This source has six open TCP connections. The limit is reached for HTTP/1.0 and HTTP/1.1 only. Waiting for an unavailable TCP socket to be released
    3. The browser is temporarily allocating space in the disk cache, generating disk cache entries (usually very quickly)
  • 例 句 : Stalled – The time spent waiting before a request was sent. It can be blocked for any reason it enters the queue, including the broker negotiation time. The request may be stopped for any of the reasons described in Queueing.

  • DNS Lookup – The browser is resolving the requested IP address, and each new domain on the page requires a full roundtrip to perform a DNS lookup

  • Proxy Negotiation – The browser is negotiating a request with the Proxy server

  • Initial Connection – The time required to establish the connection, including TCP handshakes/retries and negotiated SSL.

  • SSL Handshake – Time taken to complete the SSL handshake

  • Request Sent – The time it takes to send a network Request, usually a fraction of a millisecond.

  • Waiting – The Time it takes To wait for the initial response, also known as Time To First Byte. In addition to the time spent waiting for the server to deliver the response, this time includes a round-trip delay and the time the server takes to prepare the response (the time the server takes to send the data).

  • Content Download – The time taken to receive the response data (from the first byte received to the last byte downloaded)

  • ServiceWorker Preparation – The browser is starting the ServiceWorker

  • Request to ServiceWorker – Sending a Request to a ServiceWorker

  • Receiving Push – The data the browser is pushing through the HTTP/2 server to receive this response

  • Reading Push – The browser is Reading previously received local data

(5) the Summary area

Request the total number of requests to view | transferred to view request the total size of the | | resources resources Finish all the HTTP request and response time | | DOMContentLoaded time load time

DOMContentLoaded is triggered when the initial tag for the page is parsed. It appears on the Network panel:

  • The blue vertical line in the Overview pane represents this event.
  • The red vertical line in Requests Table also represents this event.
  • In the Summary pane, you can view the exact time of the event.

The LOAD event is triggered when the page is fully loaded. It is also displayed at:

  • This event is represented by a red vertical line in the Overview pane.
  • The red vertical line in Requests Table also represents this event.
  • In Summary, you can view the exact time of the event

DOMContentLoaded will take less time than Load, with the difference roughly equal to the time it takes for an external resource (typically an image/font) to Load

The Finish time is the time it takes for all HTTP requests on the page to be sent until the response is complete (this value will also add up if the page has a polling interface). The HTTP1.0/1.1 protocol limits the number of concurrent requests for a single domain name to 6, i.e. Finish is the time that all requests (not just XHR requests, but also DOC, IMG, JS, CSS, etc.) are completed with a concurrent limit of 6.

  • Finish takes more time than Load, which means the page has a fair amount of requests
  • The Finish time is smaller than the Load time, which means that there are fewer page requests. If the page is a static page with only one HTML document request, the Finish time is roughly equal to the HTML document request time

So the Finish time is not directly related to DOMContentLoaded and Load

Use the Network panel for Network tuning

Refer to the Network panel for some optimization suggestions for the Network

Queue or stop blocking

The most common problem is that many requests are queued or blocked. This indicates that too many resources are being retrieved from a single client. In the HTTP 1.0/1.1 connection protocol, Chrome limits the number of TCP connections to six per domain name. If twelve resources are requested at once, the first six will start and the last six will queue. Once one of the requests is complete, the first request item in the queue begins its request process.

To solve this problem with traditional HTTP 1, you need to provide service resources in multiple subdomains, split the resources into multiple subdomains and distribute them evenly.

If HTTP 2 is deployed, do not domain the resource, as it will affect how HTTP 2 works (TCP connection multiplexing in HTTP 2). The six-connection limit of HTTP 1 is removed, and multiple resources can be transferred simultaneously over a single connection.

The time to receive the first byte is slow

The green blocks occupy a high proportion:

TTFB is the time to wait for the first response byte. It is recommended to wait less than 200ms. The following conditions may cause high TTFB:

  1. The network between the client and server is poor
  2. Or, the server-side program is slow to respond

To solve high TTFB, first eliminate as many network connections as possible. Ideally, host the application locally (deployed locally) and see if you still have a large TTFB. If so, you need to optimize the response speed of the application needle. This might mean optimizing database queries, implementing caching for parts of content, or modifying the Web server configuration. There are many reasons why the back end might be slow. You need to research your program and find out what doesn’t fit your expectations.

If the local TTFB is low, there is a network problem between your client and server. Network traffic can be disrupted by many things. There are a number of points between the client and server, each with its own connection restrictions, that can cause problems. The easiest way to test for reducing this is to put your application on another host and see if TTFB improves.

Slow loading

Blue blocks occupy a high proportion:

If the Content Download phase takes a lot of time, optimizing for faster service response, parallel downloads, etc., won’t help much. The main solution is to send fewer bytes (for example, a large high-quality image may be a few megabytes in size, where the width, height and/or sharpness of the image can be optimized)

Sources panel

This section can be eaten with /devtools/debug-js/get-started

Mainly used to debug the JavaScript in the page

Custom Snippets

We often have JavaScript code that we want to debug on the console, and if it’s too much code to write directly in the console, or we often have snippets of code that we want to save (stabilization, throttling, getting address bar parameters, etc.) These snippets are available every time you open Devtools, instead of looking for them in your notes.

Under the Sources TAB, as you can see, is the Snippets TAB, where you can add common Snippets. (Be a little notebook)

To set breakpoints

Breakpoint panel

Interrupt at the specified location

Breakpoints debug the basic process

Find the source code, click where you want to interrupt code execution, and click where the red button is. It then triggers the method to execute, since it is known that clicking the button triggers it, so it is necessary to precisely locate the line of code:

Global event interrupt

If you don’t know where the code is executing, consider the following scenario:

The total number of lists returned by the interface should be 20, but the page reaches 15 to the bottom

It’s a bit of a problem to see how the code is written, but finding the right place to debug the compiled code is like looking for a needle in a haystack. To see if your imagined solution is correct:

  1. Because the list is a pull load, it will definitely trigger a network request, and you can type an XHR breakpoint in the event listener

  2. The pull load page then triggers the interface request and, as expected, the code interrupts execution. Sourcemap cannot be found, so temporarily turn off js resource mapping(Related solutions):

  3. The breakpoint is fired again, and you can see the code that broke, because it must be the business code on the page that pushed the request onto the execution stack, so you can find the corresponding method name: getVideoList

  4. Click on the method name to jump to the corresponding source code, you can see that the circled code and the suspected problem code should be in the same place

  5. Back to the cause of the problem: The page requests new data directly afterpageNumThe current list length is compared to the total number of data returned by the interface.

  6. Remember the code you want to change, at the beginning of this file, which is 191.xxx.js

    1. Put a breakpoint on the first line and a breakpoint before the push method:(If it doesn’t refresh again (it’s not clear why it might not))
    2. Then refresh the page and find the code you just wanted to change: uset.recommendList.lengthreplacen.pageSize*t.pageNo(The first two steps are to prevent js from starting to parse the problem code, so first block the run:stackoverflow)
  7. againCtrl + S“, and then look at the page effect, the list can load fully:

There is no direct support for modifying the page code in the Beautify Code panel

The black box model

By putting a script file in a Blackbox, you can ignore the call stack from a third-party library

Default (black box not enabled) :

Open the black box:

  • Opening mode ①

    1. Open the DevToolsSettings(set)
    2. On the left navigation menu, clickBlackboxing(black box)
    3. Click on theAdd pattern...Add Mode button.
    4. inPatternPattern text box enter the file name pattern that you want to exclude from the call stack. DevTools will exclude any scripts that match this pattern.
    5. In the drop-down menu to the right of the text field, selectBlackbox(black box) to execute the script file but exclude calls from the call stack, or selectDisabled(disable) to prevent file execution.
    6. Click on theAdd(Add) Save
  • Open mode ② Blackbox script directly on the stack information you want to ignore

DOM breakpoint

View the Element panel DOM breakpoints

The Performance panel

This chapter please use Chrome’s incognito mode open/devtools jank/index. The HTML Stealth mode can guarantee the Chrome running under a relatively clean environment. If you have many Chrome plug-ins installed, they may affect the analysis performance

In the Performance panel, you can view detailed information about the page loading process, such as when you started what, how long it took, and so on. Compared with the Network panel, you can not only see the information of loading resources through the Network, but also see the information of analyzing JS, calculating style, redrawing and other aspects of page loading

The main area of the panel is divided into:

  1. Controls – Start recording, stop recording and configure information captured during recording

  2. Overview – A summary of page performance

  3. Flame Chart – [Flame Chart (thread panel)]. See three vertical dotted lines (the green one has several) on the flame chart:

    • The blue line represents theDOMContentLoadedThe event
    • The green line is when it was first drawn
    • Red line represents theloadThe event
  4. Details – In the Flame Chart, after you select an event, this section displays more information about that event;

    If a frame is selected, this section displays information about the selected frame. If neither the event nor the frame is selected, this section displays information about the current recording period.

Start recording

  1. First, click the first circle on the left of the control bar to start logging
  2. Wait a few minutes (normal operation page)
  3. By clicking the Stop button, Devtools stops recording, processes the data, and displays the performance report

And then you get the picture above

Mobile devices have much less CPU power than desktops and laptops. Whenever a page is analyzed, CPU limits are used to simulate how the page will behave on a mobile device. In Development Tools, click the Performance TAB. Make sure the Screenshot check box is enabled. Click “Capture Settings”. The Capture SettingsDevTools reveals the Settings related to how to Capture performance metrics. For the CPU, choose 2x deceleration. DevTools will limit the CPU to two times slower than usual

Note: If you want to make sure they work well on low-end mobile devices, set the CPU limit to 20x deceleration.

(1) Controls control bar area

  • The upper region
    • ScreenshotsScreenshot: Selected by default, every frame will take a screenshot
    • MemoryMemory consumption Record: You can see various memory consumption curves
  • The checkbox area below
    • Disable javaScript samples[Disable javaScript example] : Reduce the overhead of the system while the phone is running
    • Network[Network simulation] : Can simulate running pages in 3G,4G and other network conditions
    • Enable advanced paint instrumentation(slow)[Enable advanced drawing detection tools (slow)] : Capture advanced drawing detection tools with significant performance overhead
    • CPU[CPU limited performance] : Mainly to simulate the performance of the base CPU

(2) Overview Area

FPS

The higher the green bar, the higher the FPS. The red blocks on the FPS diagram (at the beginning of the figure above) represent long frames that are likely to stall. You’ve played games enough to know what this metric means. 120FPS means smooth (manual funny)

The FPS of the flame diagram quantifies this parameter

Frames per Second (FPS) is a key performance metric used to analyze animations. At 60 FPS, the user experience is good

Q: why 60fps?

A: our goal is to ensure that the page has A refresh rate higher than 60fps(frames) per second, which is consistent with the refresh rate of most current monitors (60Hz). If the web animation is at 60 frames per second, it will refresh in sync with the display for optimal visual effects. This means that 60 re-renders can be done in one second, with each re-render taking no more than 16.66 milliseconds

CPU

CPU resources. This area chart indicates the type of event consuming CPU resources. The colors in the CPU chart correspond to the colors in the Summary panel, which is located just below the Performance panel. The colors in the CPU chart represent the amount of time the CPU spent on various kinds of processing during this time period. If you see a process taking a lot of time, that might be a clue to a performance bottleneck

Color division of CPU resource Area map:
color Perform content
Blue (Loading) Network communication and HTML parsing
Yellow (Scripting) JavaScript execution
Purple (Rendering) Style calculation and layout, known as rearrangement
Green (Painting) Change appearance without affecting layout, redraw
Gray (other) Time spent by other events
White (Idle) Free time

Redraw is when a node needs to change its appearance without affecting the layout, such as changing its color. Backflow (rearrangement) is when the layout or geometry needs to be changed

A rearrangement must result in a redraw, and a redraw does not necessarily result in a rearrangement. The cost of rearrangement is much higher, and changing the deeper nodes is likely to lead to a series of rearrangements of the parent nodes

Style -> layout -> paint -> composite

Summary of performance optimization

NET

Each colored bar represents a resource. The longer the bar, the longer it takes to retrieve the resource. The light part of each bar represents the wait time (the time from the request of the resource to the completion of the first byte download) and the dark part represents the transfer time (the time between the first byte download and the last byte download)

  • HTML: blue
  • CSS: purple
  • JS: yellow
  • Photo: Green

To optimize network performance, use the Network panel directly

3. Flame Chart (Thread panel)

Analyze the time consumption of certain tasks to locate problems

A few dotted lines to see:

  • The blue line represents theDOMContentLoadedThe event
  • The green line is when it was first drawn
    • FP(First Paint): First Paint
    • FCP(First Contentful Paint) : First Contentful Paint
    • FMP(First Meaningful Paint) : First Meaningful Paint
    • Largest Contentful Paint (LCP) : Largest area content drawing
  • Red line represents theloadThe event
  • DOMContentLoaded: The CONTENT of the DOM has been loaded. So what is the end of dom content loading? Open a web page when entering a URL, the display of the page is blank first, and then after a while, the page will show the content, but some of the resources of the page such as picture resources can not be seen, at this time the page can be normal interaction, after a period of time, the picture is displayed on the page. The DOMContentLoaded event is triggered when the page goes blank and the page content is displayed. This is when the HTML document is loaded and parsed.

  • Load: The load event is not triggered until all the resources on the page (images, audio, video, etc.) have been loaded. In short, the page’s load event is not triggered until DOMContentLoaded has been fired.

Main

Looking at the main thread, Devtools shows how the main thread is running

  • The X-axis is time. Each bar represents an Event. The longer the bar, the longer the event takes.
  • The Y-axis represents the call stack. In the stack, the event at the top calls the event at the bottom

Examples of official Google docs:

As shown above: the click event triggers a function call on line 53 of script_foot_closure. Looking below, Function Call can see that an anonymous Function is called, then Me() is called, then Se() is called, and so on.

DevTools assigns random colors to scripts. In the figure above, the function call from a script is shown in light green. The call from another script is rendered beige. The darker yellow represents script activity, and the purple event represents render activity. These darker yellow and purple events are consistent across all records.

  1. In performance reporting, there is a lot of data. You can double click, drag, and so on to zoom in and out of the report to view the analysis report from a variety of time periods
  2. If a small red triangle appears at the upper right corner of the event bar, it indicates that the event is problematic and needs special attention
  3. Double click on the event with the little red triangle. You can see the details in the Summary panel. Notice the Reveal link. Double-click on it to highlight the event that triggered the event. If you click the app.js:94 link, you will be redirected to the corresponding code

(4) the Details area

Usually used with the Flame Chart

  • SummaryThe area is a pie chart overview of the total time spent by each event type, plus three viewing options:
  • Bottom-UpTAB: Used when you want to see the activities that directly spend the most time
  • Call TreeTAB: Used when you want to see the root activities that cause the most work
  • Event LogTAB: Used when you want to view activities in order of activity during the recording period

Window. The performance object

The Performance interface can obtain performance-related information on the current page. It’s part of the High Resolution Time API, It also integrates Performance Timeline API, Navigation Timing API, User Timing API and Resource Timing API.

The Performance object is essentially a performance monitoring object, with almost all the performance parameters required by the common front end built in

performance API

performance API

  • memory

    • TotalJSHeapSize: ‘Available memory size’ // Unit: KB
    • UsedJSHeapSize: ‘Used memory size’
    • JsHeapSizeLimit: ‘Memory size limit’
  • navigation

    • redirectCount: 0

      If there is a redirect, the page is redirected several times

    • type: 0

      Similar to the scene value defined by the applet, the value of type: 0 refers to the normal TYPE_NAVIGATENEXT page (not refreshed, not redirected, etc.) 1 refers to the TYPE_RELOAD page refreshed by windox.location.reload () 2 refers to the TYPE_BACK_FORWARD The page (history) 255 that is entered through the forward and back buttons of the browser is the page that TYPE_UNDEFINED is not entered through the above methods

  • Onresourcetimingbufferfull / / a when resourcetimingbufferfull events trigger calls EventHandler resources time performance of the event when the browser will trigger buffer is full

    / / on the onresourcetimingbufferfull attribute set a callback function: the function buffer_full (event) {the console. The log (" WARNING: Resource Timing Buffer is FULL!" ); performance.setResourceTimingBufferSize(200); } function init() { // Set a callback if the resource buffer becomes filled performance.onresourcetimingbufferfull = buffer_full; } <body onload="init()"Copy the code
  • TimeOrigin: 1594219100175.9412

    Returns a high-precision timestamp of the time at which the performance measurement began

  • timing

    • NavigationStart: ‘timestamp’

      In the same browser context, the timestamp of an unload page for the previous page (not necessarily in the same domain as the current page) is equal to the fetchStart value if there is no previous page unload;

    • unloadEventStart: 0

      The timestamp for the previous page unload (same domain as the current page), or 0 if there was no previous page unload or the previous page was in a different domain from the current page

    • unloadEventEnd: 0

      Corresponds to unloadEventStart, returns the timestamp of wang Bi executed by the callback function bound to the previous webpage unload event

    • redirectStart: 0

      The time when the first HTTP redirection occurs, if there is a jump and the redirection is within the same domain name, otherwise the value is 0

    • redirectEnd: 0

      The time when the last HTTP redirection is complete, if the redirect is within the same domain name, otherwise the value is 0

    • FetchStart: ‘timestamp’

      The time the browser is ready to grab the document using an HTTP request, which occurs before checking the local cache

    • DomainLookupStart: ‘timestamp’

      The start time of the DNS domain name query, which is equal to the fetchStart value if local caching (that is, no DNS query) or persistent connections are used

    • DomainLookupEnd: ‘timestamp’

      The completion time of the DNS domain name query, which is equal to the fetchStart value if local caching (that is, no DNS query) or persistent connections are used

    • ConnectStart: ‘timestamp’

      The time at which HTTP(TCP) starts to establish a connection, which is equal to the fetchStart value if the connection is persistent. If an error occurred at the transport layer and the connection was re-established, the time when the new connection was established is shown

    • ConnectEnd: ‘timestamp’

      The time HTTP(TCP) takes to complete the establishment of the connection (handshake), which is the same as fetchStart if the connection is persistent; If an error occurs at the transport layer and the connection is re-established, then this is the time to complete the newly established connection in Xianning; this

    • secureConnectionStart: 0

      The time the HTTPS connection starts. If the connection is not secure, the value is 0.

    • RequestStart: ‘timestamp’

      The start time of the HTTP request to read the real document (completion of the connection), including reading from the cache locally, and showing the time of the new connection in case of a connection error

    • ResponseStart: ‘timestamp’

      The time at which HTTP begins to receive a response (getting the first byte), including reading the cache locally

    • responseEnd: 0

      The time when the HTTP response is fully received (the last byte is obtained), including the cache read locally

    • domLoading: 0

      This is when document. readyState becomes interactive and the readyStatechange event is thrown. (This is just the end of parsing the DOM tree

    • dominteractive: 0

      At the time the DOM tree is parseable, Document and readyState will become interactive and the event related to ReadyStatechange will be thrown (the page resource has not been loaded yet).

    • domContentLoadedEventStart: 0

      The time when resources in a web page begin to load after DOM parsing is complete and before the DOMContentLoaded event is thrown

    • domContentLoadedEventEnd: 0

      After DOM parsing is complete, the time when the resources in the web page are loaded

    • domComplete: 0

      When the DOM tree is parsed and the resource is ready, Document.readyState becomes complete and a ReadyStatechange-related event is thrown

    • loadEventStart: 0

      The load event is sent to the document, which is the time the load callback starts to execute. If no load event is bound, the value is 0

    • loadEventEnd: 0

      The time at which the callback function for the load event completes execution

Several useful apis

The performance. Now () method

The performance. Now () returns the performance. NavigationStart to the current number of milliseconds. Performance. NavigationStart is below will be introduced to the measurement point can be said to be the browser to access the first time.

Two points to note:

  • The initial measurement point is the browser’s access to the initial measurement point, or understood as the moment you enter a URL in the address bar and press Enter.
  • The return value is the number of milliseconds, but with a precise multi-place decimal.

Check the execution time (milliseconds) of js code with performanc.now () :

var st = performance.now(); console.log(Array(9999999).fill(null).filter(v => ! v).length); var end = performance.now(); Console. log(' value time ${end-st}ms'); // Value time 558.7849999992759ms Copy codeCopy the code

performance.navigation

Performance. Navigation is responsible for recording user behavior information and has only two properties:

  • redirectCount
    • If there is a redirect, the page is redirected several times
  • type
    • The value of the type:
    • 0 isTYPE_NAVIGATENEXTEnter the page normally (no refresh, no redirection, etc.)
    • 1 theTYPE_RELOADThe page is refreshed via window.location.reload()
    • 2 theTYPE_BACK_FORWARDPage accessed via the browser’s back and forward buttons (history)
    • 255 that isTYPE_UNDEFINEDThe page is not accessed using the preceding methods
console.log(performance.navigation); PerformanceNavigation. {type: 1, redirectCount: 0} Replication codeCopy the code
performance.timing

Timing contains almost all timing nodes

You can use this field to count the occurrence duration of related events on the page:

function getTiming() { try { var timing = performance.timing; var timingObj = {}; var loadTime = (timing.loadEventEnd - timing.loadEventStart) / 1000; if(loadTime < 0) { setTimeout(function() { getTiming(); }, 0); return; } timingObj[' timing '] = (Timing.redirectend.redirectstart); TimingObj [' timing '] = (timing. DomainLookupEnd - timing. DomainLookupStart); TimingObj ['TCP handshake time '] = (Timing. Connectend.timing. ConnectStart); TimingObj ['HTTP request complete time '] = (timing. TimingObj [' time spent before DOM starts loading '] = (Timing. Responseend-timing. TimingObj [' DOM loaded time] = ((timing. DomComplete | | timing. DomLoading) - timing. DomLoading); TimingObj [' domtiming '] = (timing. DomInteractive - timing. DomLoading); TimingObj [' Total network interaction time, i.e. '] = (Timing. ResponseEnd - Timing. TimingObj [' interactive time] = (timing. DomContentLoadedEventEnd - timing. DomContentLoadedEventStart); TimingObj [' First occurrence '] = (timing. DomLoading - Timing. NavigationStart); TimingObj [' onLoad event time '] = (timing. Loadeventend-timing. LoadEventStart); TimingObj [' page loading time '] = (timingObj[' redirection time '] + timingObj['DNS resolution time '] + timingObj['TCP handshake completion time '] + timingObj['HTTP '] Request/response completion time '] + timingObj['DOM completion time '] + timingObj['DOM loading completion time ']); for(item in timingObj) { console.log(item + ":" + timingObj[item] + '(ms)'); } console.log(performance.timing); } catch(e) { console.log(performance.timing); }} window.onload = getTimingCopy the code
performance.memory

Displays the current memory usage

console.log(performance.memory) /* { jsHeapSizeLimit: 4294705152, totalJSHeapSize: 13841857, usedJSHeapSize: 12417637} */ Copy codeCopy the code
  • UsedJSHeapSize indicates the memory used by JS objects (including internal objects of the V8 engine)
  • TotalJSHeapSize indicates the available memory
  • JsHeapSizeLimit: Memory size limit

In general, usedJSHeapSize cannot be greater than totalJSHeapSize; if it is, there may be a memory leak.

performance.getEntries()

When the browser gets a web page, it makes an HTTP request for every object in the web page (script files, style sheets, image files, and so on). The performance. GetEntries method returns a list of PerformanceEntries in the form of an array, with statistics on the time of these requests and the number of members in the returned array depending on how many requests there are

  • name: links to resources
  • durationTotal resource time (including wait time, request time, response time equal to responseend-starttime)
  • entryTypeThe structure of the objects in the array varies from one array to another:
    value Object of this type describe
    mark PerformanceMark An object added to the array via the mark() method
    measure PerformanceMeasure An object added to the array via the measure() method
    paint PerformancePaintTiming The value is first-paint’ first draw, ‘first-contentful paint’ first content draw.
    resource PerformanceResourceTiming All resources load time, the most useful
    navigation PerformanceNavigationTiming Navigation information is not supported except for Chrome and Opera
    frame PerformanceFrameTiming None of the current browsers supports it
  • initiatorType: How to initiate the request, the initial type (note that this type is not accurate, for example in CSS image resources will display CSS with this value, so it is recommended to use the suffix in name)
    A object value describe
    a Element The link/script/img/iframe, etc The resource is loaded as a label, with the value in lowercase of the node name
    a CSS resource css Resources loaded with CSS styles, such as background urls
    a XMLHttpRequest object xmlhttprequest/fetch Resources loaded through XHR
    a PerformanceNavigationTiming object navigation When the object is PerformanceNavigationTiming returns
performance.getEntriesByType()

Method returns a list of getEntries for the given type to open the page

This code can be run in the DevTools console. It uses the Resource Timing API to retrieve all resources. It then filters entries, looking for entries that contain the name lok-1024px.png. If found, the relevant information is returned.

Performance. GetEntriesByType ('resource').filter(item => item.name.includes('logo-1024px.png')) Copy codeCopy the code

Note: The connectEnd related field that returns the resource is not a Unix timestamp, but DOMHighResTimeStamp. MDN PerformanceResourceTiming

DOMHighResTimeStamp is a double that stores the time value. The value can be a discrete time point or the time difference between two discrete time points. T indicates milliseconds. The value should be accurate to 5 µs (microseconds). However, if the browser is unable to provide a time value accurate to 5 microseconds (for example, due to hardware or software limitations), the browser can represent the value in milliseconds in milliseconds

The Lighthouse (Audits) panel

Text description from Google: Lighthouse is an open source automation tool designed to improve the quality of web applications. You can run it as a Chrome extension or from the command line. You give Lighthouse a url that you want to review, it runs a series of tests against that page, and then generates a report on the page’s performance

Page loading is analyzed and recommendations are made to improve page performance

👍 for lazy people

There are five indicators:

  • Performanceperformance
  • accessibilityAccessible use
  • Best PracticeThe user experience
  • SEOSEO optimization
  • Progressive Web AppPage compatibility with PWA

Security panel

Used to test the security of the face to face page

This panel can distinguish between two types of insecure pages:

  • If the requested page is served over HTTP, the primary source is marked as insecure.
  • If the requested page is obtained over HTTPS, but the page then continues to retrieve content from another source over HTTP, the page is still marked as insecure. This is known as a mixed content page, and mixed content pages are only partially protected because HTTP content (non-encrypted content traffic in plain text) can be eavesdropped and is vulnerable to man-in-the-middle attacks. For example, in 163, although the certificate is valid, the page has part of the HTTP resource:

Command’s ultimate move

With the console open, press Ctrl + Shift + P/Command + Shift + P to open the Commands menu

screenshots

If you only want to take a screenshot of a specific DOM node, you may need to use other tools for a long time. Using the console, you can simply select the node you want to take a screenshot of, open the Command menu, and use the node to take a screenshot

  • Intercepting a specific node:Screenshot Capture node screenshot
  • Full screen capture:Screenshot Capture full size screenshot

CSS/JS coverage

Media queries

Media inquiries are an essential part of adaptive web design. In Device mode in Chrome Devtools, click on the three-dot menu to enable Show Media queries:

Right-click on a bar to see where the media query is defined in the CSS and skip to the definition in the source code

reference

  • Why do Chrome Network, Size and Time have two lines of arguments
  • Chrome Developer Tools
  • Google chrome-devtools
  • Chrome DevTools uses a detailed — Performance
  • New Chrome Devtool Performance Guide
  • Chrome- Performance page performance analysis tutorial
  • MDN Performance
  • Web performance detection – Performance
  • Detailed browser rendering process
  • Chrome sets various postures for breakpoints
  • Network Summary