preface

Chrome DevTools has really been the closest friend of front-end development since I graduated from the workforce. Through the continuous learning and use of Chrome DevTools during this period of time, I have also summarized a set of my own experience in using Chrome DevTools. Here I will also classify my summary, share it and discuss with you. The first two categories will be introduced in this article, and other related categories will be introduced in the following articles. Please stay tuned

In this article, I will introduce the console syntax and the command menu syntax in a step-by-step manner. In this article, I will clearly and intuitively show the benefits of some of the usages I recommend, and I hope you can make suggestions or supplements to create a personalized Chrome devTools article ~

Console fancy play

This section will focus on two different aspects of console, including application scenarios for API methods other than console.log and a code demo that uses variable printing.

Console object column

So before we do that, let’s take a look at what methods are in the Console object.

So I’ll start from the beginning and introduce some of the more common methods in turn:

1. Assert condition judgment print: console.assert()

In a specific environment or scenario, you want to print specific logs without affecting the continuation of program execution.

Let testValue = 10086 console.assert(testValue === 10087,' Test the value of testValue ') console.log(' Code continues to execute ')Copy the code

2. Clear the console: console.clear()

3. Count the number of times the function is executed: console.count()

console.count(); // Output: default: 1 console.count('a'); // Output: a: 1 console.count(); // Output: default: 2 console.count('b'); // Output: b: 1Copy the code

We can count the number of times a function is called, or we can pass parameters to the function, and count the number of times a function is called according to the different types of grouping of parameters.

function foo(param = '') {
  param ? console.count(param) : console.count()
}
foo()    //default: 1
foo()    //default: 2
foo()    //default: 3
foo('A') //A: 1
foo('A') //A: 2
foo('B') //B: 1
Copy the code

4. Reset count count method: console.countreset ()

Calling this method resets the count of the console.count() method

console.count(); console.countReset(); console.count(); // Output default: 1 console.count('a'); console.countReset('a'); console.count('a'); // Output a: 1Copy the code

5. Print DOM object node method: console.dir()

There is not much difference in printing strings or objects from console.log(), only in the presentation form. But when it comes to printing DOM objects, console.log() prints in pure label format, whereas console.dir() prints out dom tree object format.

Console.dirxml () is the HTML/XML code contained in a node that displays a web page.

6. Common methods: console.log(),info(),warn(),error()

Log (' prints general information ') console.info(' prints suggestive information ') console.warn(' prints warning information ') console.error(' Prints error information ')Copy the code

Notice here that Default levels are highlighted in red. Verbose (Verbose),Info (Info), Warnings (warning), and Error (Error) are sorted by severity levels. We can Filter the information printed by the console by selecting the drop-down box with the function of Filter.

7.1 Group Output: console.group(),groupEnd()

Sometimes you want to make your printed information more intuitive, you can choose to view it in groups, and you can fold/expand it in the console.

Console. group(' Receiving information '); // Outer group console.log('name: junjun '); console.log('telephone: 188xxxx3135'); Console. group(' harvest address '); // Inner group console.log('city: Beijing '); The console. The log (' canal street: times'); console.groupEnd(); console.groupEnd();Copy the code

7.2 the console. GroupCollapsed

This is similar to the console.group method, but it is folded up when first displayed on print and needs to be expanded manually.

Console. GroupCollapsed (' information '); // Outer group console.log('name: junjun '); console.log('telephone: 188xxxx3135'); Console. GroupCollapsed (' harvest address '); // Inner group console.log('city: Beijing '); The console. The log (' canal street: times'); console.groupEnd(); console.groupEnd();Copy the code

8. Table output: console.table()

It can convert data of compound type, that is, array object type, to table form.

Var arr = [{name: 'Wu Yifan ', varietyShow:' New Rap in China '}, {name: 'Zhang Yixing ', varietyShow:' Extreme Challenge '}, {name: 'Lu Han ', varietyShow: }, varietyShow: 'Creation camp'},] console.table(arr)Copy the code

9. Test execution time or execution efficiency: console.time(),timeLog(),timeEnd()

The time() method can start a new timer and is useful for measuring how much time something takes. If you want to stop the timer, you can call timeEnd() and pass it the same string as the initializer. The console then records the label and the elapsed time when the timeEnd() method fires.

console.time("test loop"); for (var i = 0; i < 100000000; I++) {// start loop} console.timeEnd("test loop"); / / test loop: 221.094970703125 msCopy the code

The output in the following example prints the record time from the user opening the page to closing the first alert, and the record time from closing the second alert.

console.time("record time"); alert("continue"); console.timeLog("record time"); alert("continue again"); console.timeEnd("record time"); // Record time: 2754.39599609375 MS // Record time: 5741.634033203125msCopy the code

10. Call stack to trace code: console.trace()

function addSum(a,b){ console.trace(); return a+b; } var x = addSum3(1,1); function addSum3(a,b){return addSum2(a,b); } function addSum2(a,b){return addSum1(a,b); } function addSum1(a,b){return addSum(a,b); }Copy the code

11. Performance analysis: console.profile()

function doTask(){ doTaskA(1000); doTaskB(1000000000); 00 doTaskC (1000100); } function doTaskA(count){ for(var i=0; i<count; i++){} } function doTaskB(count){ for(var i=0; i<count; i++){} } function doTaskC(countX,countY){ for(var i=0; i<countX; i++){ for(var j=0; j<countY; j++){} } } console.profile(); doTask(); console.profileEnd();Copy the code

To view the performance panel in Chrome, instead of printing it directly from the console, click the three dots in the upper right corner and click the Javascript Profiler under More Tools.

Two. Variable print column

On the page of jingdong main website, we will see the following text in the console. Let’s briefly analyze its implementation.

Before analyzing, summarize the knowledge points:

  1. % s string
  2. Integer %d or % I
  3. % f floating point number
  4. % o % o object
  5. % c CSS styles

Then jingdong main station of this string of text, we can use % C CSS style plus \ N line to achieve, the specific code is as follows:

Console. log('%c ') This page was developed by Bump Lab (JDC- Experience Technology Department) and you can find out about us at https://aotu.io. \n\n If you are also interested in what we are doing, please join [email protected] (note from console) \n\n This project proudly uses the Nerv framework produced by Concave-Bump Lab. You can learn more about the related content and ecology on our website. \n https://nerv.aotu.io/','color:#1890ff'Copy the code

Note: Hyperlinks in console.log prints are automatically recognized and styled with grey font colors and underscores, which cannot be overridden with % C CSS styles.

Console built-in command column

Similar to jquery, you can directly select DOM elements, trigger events, monitor events, add and remove elements, and so on from the Console panel.

Here are the basic uses of the various $formats:

1. $_ : Records the result of the last console run for the next time

2. $x: Returns the matched node in an array based on the expression

Here is an example of matching elements in our project’s Beautiful Diary

$x (' / / li) match all li element tag $x (' / / li / / a) match all li element under a element tag $x (' / / li [a] ') matches all li element contains a element tagCopy the code

3.
0 . 0,
1,
2 . 2,
3,
4 . 4,
5: represents the five DOM nodes you recently selected

Use the project as an example

4. $$(‘ XXX ‘) : returns the meet all the conditions of a collection, similar to the document. The querySelectorAll () encapsulation

2. Fancy operation command menu

Devtools is already very powerful, but the panel can’t be all of them at once. We can use Windows(CTRL + Shift + P) or Mac(Command + Shift + P) to open and input the function we want to implement. Here I will elaborate on the six modules commonly used in my daily work projects

1: Print results with timestamp format

Enter “show timestamps” in the command menu to add timestamps to the result.

2: Monitoring FPS indicator tool

The tool displays a real-time FPS panel, showing the FPS indicators of the page, and observing the memory usage during interface interaction.

You can enable this function by using the Show Frames per second(FPS) meter.

When activated, you can observe a black area in the upper left corner of the page that contains real-time data for the frames. With this tool, we can observe in real time what we see directly in the process of manipulating the page that causes the page frame refresh rate to drop.

If the animation is running at 60FPS, it looks smooth. Anything less than 60FPS means that some frames take too long to render, and the animation looks sloppy or even cluttered, leaving the page in dire need of polish. Another thing shown in the FPS meter is GPU memory usage, which in the previous figure was 2.3MB out of 512MB, which means GPU usage is low.

3: More powerful Performance Monitor The Performance Monitor

Sometimes when we are optimizing a project or a page in javascript or CSS, we want to find an intuitive way to locate the effect of our optimization. In this case, you can use the Performance Monitor to perform real-time monitoring.

Open the command menu and enter > Show Performance Monitor to start the Performance Monitor. The Performance indicators are as follows:

CPU Usage: INDICATES the CPU usage

JS head size: the size of the JS memory

DOM Nodes: indicates the number of DOM Nodes mounted in memory

JS event listeners: Number of event listeners

Layouts/SEC: A rearrangement used by the browser to calculate the location and size of all elements on a page

Style recalcs/SEC: Page Style redraw

Here I recommend an article by Paul Irish on why Translate() moves better than Top/Left. As a quick note, the top and left attributes trigger the entire pixel rendering process (involving drawing, layout, and composition), which in conjunction with animations can trigger quite a few operations per second. But the Transform property, as you can see from our recommended Performance Monitor, does not trigger drawing and layout.

4: Code coverage features

In the command menu, you can view code Coverage through the Coverage function, which applies to both JS and CSS. It gives full play to its value by dynamically collecting the percentage of code that is actually being executed during code execution. To improve the performance of WEB applications.

As shown in the small animation above, the Coverage record result table shows all the file types loaded, the usage of the file run, and the summary data. By clicking the corresponding static resource file, it will be opened in the Sources panel, green means used, red means not used.

So now we’ll talk about the use of coverage code:

In the process of recording data, if not carried out a large part of the code, means that the user when they visit our page loads too many useless code, lead to our page loading time completely, single-page application startup time slow, under slow network especially low-end equipment performance loss problem more obvious. Through research, it can be optimized from two aspects. The packaging method of Webpack mentioned below is not described at the moment, but only provides an idea. I will output a corresponding article after practice.

1) Remove dead code

A page or even a project will be developed by many people, but it will leave a lot of useless code, many people dare not delete at will, resulting in more and more useless code accumulation. We can then rely on the packaging tool to add configuration items to support the direct removal of dead code when compressing the code.

2) Lazy loading code

Sometimes a high proportion of useless code is found in coverage execution, but this does not mean that it is completely useless, but some of the code may not be used when the page is loaded, but the user’s subsequent operations may trigger those unused codes. So I’m going to give you the lazy loading idea and expect the code to be loaded when it’s needed. There are some configurations and methods in WebPack to do this, which I’ll cover in a future article. By lazy loading, you can greatly reduce the amount of code that a page has to download for the first time and improve performance.

5: Page screenshot function

You can use a Screenshot from a DOM node using a Screenshot capture node.

Or sometimes if you want to get a full screen Screenshot, go to the Screenshot Capture full size Screenshot command.

** Note: ** The effect of a full screen shot is not just a partial shot of the visible area of the page, but of the content of the entire page, including the scroll bar.

6: Check the animation function

When we turn on the animation check function, we can check our animation or modify our animation, and then intuitively display the function on the page. When you check, you can slow down, replay, or view the source code of the animation group. When modifying, you can modify the animation group’s time, delay (**100%, 25%, 10%** third gear), duration or keyframe offset.

How can we start with Animations? There are two ways to start. One is through the command menu: Show Animations, or open the More Tools tool with the three clicks in the upper right corner and select Animations. Here to jingdong main station as an example, to demonstrate the effect after opening.

The animation panel is mainly divided into four functions, which are explained by serial number in the figure.

  1. Controls: You can change the speed of the currently selected animation group.
  2. Overview: Here you can select an animation group to examine and modify in Details.
  3. Timeline: Pausing and starting the animation from here, or jumping to a specific point in the animation.
  4. Check and modify the currently selected animation group.

The resources

Developers.google.com/web/tools/c…

Developers.google.com/web/tools/c…

Developers.google.com/web/tools/c…

medium.com/@gilfink/qu…

medium.com/@willmendes…