Home > Web Front-end > JS Tutorial > body text

Detailed introduction to the most comprehensive summary of JavaScript debugging skills

黄舟
Release: 2017-03-08 14:49:43
Original
1006 people have browsed it

Foreword: Debugging skills are an essential skill in any technology research and development. Mastering various debugging skills will definitely get twice the result with half the effort at work. For example, it can quickly locate problems, reduce failure probability, help analyze logic errors, etc. Today, when Internet front-end development is becoming more and more important, how to reduce development costs and improve work efficiency in front-end development and master front-end development and debugging skills is particularly important.

This article will explain various front-end JS debugging skills one by one. Maybe you are already proficient in it, so let us review it together. Maybe there are methods you have never seen before, so you might as well learn them together. Maybe you don’t know how yet? Debugging, hurry up and take this opportunity to fill in the gaps.

Hardcore Debugging Master Alert

It was still the era when the Internet was just starting. The front-end of web pages was mainly focused on content display, and browser scripts could only provide very simple auxiliary functions for the page. when. At that time, web pages were mainly run in browsers based on IE6, and the debugging function of JS was still very weak. It could only be debugged through the alert method built into the Window object. At that time, it should look like this:

Detailed introduction to the most comprehensive summary of JavaScript debugging skills

It should be noted that the effect seen here is not the effect seen in the IE browser of the year, but the effect in the higher version of IE. In addition, it seems that there was no such advanced console back then, and the use of alert was also in the real page JS code. Although the debugging method of alert is very primitive, it did have its indelible value at the time, and even today, it has its place.

New Generation of Debugging King Console

As JS can do more and more things in the Web front-end, the responsibility is getting bigger and bigger, and the status is getting more and more important. The traditional alert debugging method has gradually been unable to meet the various scenarios of front-end development. Moreover, the debugging information that pops up in the alert debugging mode is not very beautiful, and it blocks part of the page content, which is really not very friendly.

On the other hand, for alert debugging information, statements like "alert(xxxxx)" must be added to the program logic to work properly, and alert will prevent the page from continuing to render. This means that after developers complete debugging, they must manually clear these debugging codes, which is really troublesome.

Therefore, the new generation of browsers Firefox, Chrome, including IE, have successively launched JS debugging consoles, supporting the use of a form similar to "console.log(xxxx)" to print debugging information on the console. It does not directly affect page display. Taking IE as an example, it looks like this:

Detailed introduction to the most comprehensive summary of JavaScript debugging skills

Okay, goodbye ugly alert popup. And the rising stars, led by the Chrome browser, have expanded the Console with richer functions:

Detailed introduction to the most comprehensive summary of JavaScript debugging skills

Do you think this is enough? The imagination of the Chrome development team really has to be admired:

Detailed introduction to the most comprehensive summary of JavaScript debugging skills

Okay, let’s go off topic a little bit more. In short, the emergence of the console and the browser's built-in Console object has brought great convenience to front-end development and debugging.

Some people may ask, does such debugging code need to be cleaned after debugging is completed?

Regarding this issue, if you verify the existence of the console object before using it, it will not cause damage to the business logic without deleting it. Of course, for the sake of clean code, after debugging is completed, these debugging codes that have nothing to do with business logic should be deleted as much as possible.

JS breakpoint debugging

Breakpoint, one of the functions of the debugger, can interrupt the program where needed, thereby facilitating its analysis. You can also set a breakpoint during one debugging. Next time, you only need to let the program automatically run to the set breakpoint position, and then it can be interrupted at the last set breakpoint position, which greatly facilitates operation and saves time. ——Baidu Encyclopedia

JS breakpoint debugging is to add breakpoints to the JS code in the browser developer tools, so that the JS execution stops at a specific location to facilitate developers to debug the JS code. Analysis and logical processing of code segments. In order to be able to observe the effect of breakpoint debugging, we prepare a piece of JS code in advance:

Detailed introduction to the most comprehensive summary of JavaScript debugging skills

The code is very simple, just define a function, pass in two numbers, and add After the last random integer, return the sum of the two numbers. Taking Chrome developer tools as an example, let's take a look at the basic method of JS breakpoint debugging.

Sources Breakpoint

First of all, in the test code, we can see from the console output in the figure above that the code should be running normally, but why should it be? Because a random number is added to the function, is the final result really correct? This is a meaningless conjecture, but suppose I want to verify it now: the two numbers passed in by the function, the random numbers added, and the final sum. So how to do it?

Method 1, the most common one mentioned before, whether using alert or console, we can verify it like this:

Detailed introduction to the most comprehensive summary of JavaScript debugging skills

From the above figure, we find that Three lines of console code have been added to the code to print the data variables we care about. In the end, the output results from the console (Console panel) can clearly verify whether the entire calculation process is normal, and thus achieve our problem. verification requirements.

Method 2. The verification process of Method 1 has an obvious drawback, which is that it adds a lot of redundant code. Next, let’s see if it is more convenient to use breakpoints for verification. Let’s first look at how to add breakpoints. , and what the effect will be after the breakpoint:

Detailed introduction to the most comprehensive summary of JavaScript debugging skills

As shown in the figure, the process of adding a breakpoint to a piece of code is "F12 (Ctrl + Shift + I) to open the development tools" - - "Click the Sources menu" - "Find the corresponding file in the tree on the left" - "Click the line number column" to complete the operation of adding/deleting breakpoints on the current line. After the breakpoint is added, refresh the page and JS execution stops at the breakpoint position. You will see all the variables and values ​​in the current scope on the Sources interface. You only need to verify each value to complete the verification requirements of our question.

Here comes the problem. Careful friends will find that when my code is executed to the breakpoint, the displayed values ​​​​of variables a and b have been added, and we cannot see the call to sum. The function is initially passed in 10 and 20. Then what should be done? It’s time to go back and learn some basic knowledge of breakpoint debugging. After we open the Sources panel, we will actually see the following content in the interface. Let’s follow the mouse trajectory to see what it means one by one:

Detailed introduction to the most comprehensive summary of JavaScript debugging skills

From left to right, each icon represents The functions are:

  • Pause/Resume script execution: Pause/resume script execution (program execution stops at the next breakpoint).

  • Step over next function call: Execute the function call to the next step (jump to the next line).

  • Step into next function call: Enter the current function.

  • Step out of current function: Jump out of the currently executing function.

  • Deactive/Active all breakpoints: Close/enable all breakpoints (will not cancel).

  • Pause on exceptions: Automatic breakpoint setting for exceptions.

At this point, the function keys of breakpoint debugging are almost introduced. Next, we can look at our program code line by line, and check our variables after each line is executed. The changes are as shown in the figure below:

Detailed introduction to the most comprehensive summary of JavaScript debugging skills

As above, we can see that the variables a and b change from the initial value to the random value in the middle, and then to the final calculation The entire process of summarizing and outputting the final results is easy to complete the verification requirements of the question design.

For the remaining function keys, we slightly change our test code and use a gif picture to demonstrate their use:

Detailed introduction to the most comprehensive summary of JavaScript debugging skills

Needed here Note that the function of printing variable values ​​directly in the code area is a new function only added to newer versions of Chrome browsers. If you are still using an older version of Chrome browsers, you may not be able to directly print variable values ​​​​in the case of breakpoints. To view variable information, you can move the mouse over the variable name and pause briefly, and the variable value will appear. You can also use the mouse to select the variable name, then right-click and "Add to watch" to view it in the Watch panel. This method also applies to expressions. In addition, you can also switch to the Console panel under a breakpoint, enter the variable name directly in the console, and press Enter to view the variable information. This part is relatively simple. Considering the space issue, no diagram demonstration will be given.

Debugger breakpoint

The so-called Debugger breakpoint is actually named by me myself. I don’t know how to use the professional terminology. Specifically, by adding a "debugger;" statement to the code, a breakpoint will be automatically reached when the code is executed. The next operation is almost exactly the same as adding breakpoint debugging in the Sources panel. The only difference is that you need to delete the statement after debugging.

Since the function is the same as adding breakpoints in the Sources panel except for the different ways of setting breakpoints, why does this method still exist? I think the reason is this: During development, we occasionally encounter asynchronous loading of html fragments (including embedded JS code), and this part of the JS code cannot be found in the Sources tree, so it cannot be added directly in the development tools. Breakpoint, then if you want to add a breakpoint to an asynchronously loaded script, then "debugger;" comes into play. Let’s see its effect directly through the gif:

Detailed introduction to the most comprehensive summary of JavaScript debugging skills

DOM breakpoint debugging

DOM breakpoint, as the name suggests, is to add a breakpoint on the DOM element. And then achieve the purpose of debugging. In the actual use of break points, the effect is ultimately implemented within JS logic. Let’s take a look at the specific effects of each DOM breakpoint in turn.

Break on subtree modifications when the internal child nodes of the node change

Today, when front-end development is becoming more and more complex, there are more and more front-end JS codes and the logic is becoming more and more complex. , a seemingly simple Web page is usually accompanied by large sections of JS code, involving many operations of adding, deleting, and modifying DOM nodes. It is inevitable to encounter situations where it is difficult to locate the code segment directly through the JS code, but we can quickly locate the relevant DOM nodes through the Elements panel of the developer tools. At this time, locating the script through DOM breakpoints is particularly important. Specifically, let’s take a look at the gif demonstration:

Detailed introduction to the most comprehensive summary of JavaScript debugging skills

The above figure demonstrates the effect of adding, deleting and exchanging sequence operations of ul sub-nodes (li) to trigger breakpoints . However, it should be noted that modifying attributes and content of child nodes will not trigger breakpoints.

Break on attributes modifications when node attributes change

On the other hand, as the business logic of front-end processing becomes more and more complex, there is an increasing reliance on the storage of some data. Strongly, storing temporary data in the (custom) attributes of DOM nodes is the preferred method for developers in many cases. Especially after the HTML5 standard enhanced custom attribute support (for example: dataset, data-*, etc.), attribute settings are used more and more, so Chrome developer tools also provide attribute change breakpoint support, the effect is roughly as follows:

Detailed introduction to the most comprehensive summary of JavaScript debugging skills

#This method also needs to be noted that any operation on the properties of the child node will not trigger the breakpoint of the node itself.

Break on node removal

This DOM breakpoint setting is very simple, and the triggering method is very clear-when the node is deleted. So usually this method should be used when executing the "parentNode.removeChild(childNode)" statement. This method is not used much.

The previously introduced debugging methods are basically the debugging methods we often use in daily development. If used properly, they can deal with almost all problems in our daily development. However, the developer tools also take into account more situations and provide more breakpoint methods, as shown in the figure:

Detailed introduction to the most comprehensive summary of JavaScript debugging skills

XHR Breakpoints

In recent years Front-end development has undergone earth-shaking changes, from being unknown at the beginning to being very popular today. Ajax drives rich Web applications and mobile WebApp single-page applications are booming. All of this is inseparable from the XMLHttpRequest object, and "XHR Breakpoints" is a breakpoint debugging function specifically designed for asynchronous use.

XHR Breakpoints演示

We can add breakpoint conditions for asynchronous breakpoints through the "+" sign on the right side of "XHR Breakpoints". When the asynchronous request is triggered, the URL meets this condition, JS Logic will automatically generate breakpoints. The breakpoint location is not shown in the demo animation. This is because the demo uses the ajax method encapsulated by jQuery. The code has been compressed and there is no visible effect. In fact, the location where the XHR breakpoint is generated is "xhr. send()" statement.

The power of XHR breakpoints is that you can customize breakpoint rules, which means that we can set breakpoints for a certain batch, a certain one, or even all asynchronous requests, which is very powerful. However, it seems that this feature is not used much in daily development, at least not by me. Thinking about it, there are probably two reasons: first, this type of breakpoint debugging requirement is not involved much in daily business; second, most front-end development at this stage is based on JS framework, and the most basic jQuery has also implemented Ajax. In order to ensure good encapsulation, few people encapsulate Ajax methods themselves. In order to reduce the code size, projects usually choose compressed code libraries, making XHR breakpoint tracking relatively difficult.

Event Listener Breakpoints

Event listener breakpoints are set based on the event name. When an event is triggered, the breakpoint is set to the location where the event is bound. Event listener breakpoints list all page and script events, including: mouse, keyboard, animation, timer, XHR, etc. It greatly reduces the difficulty of debugging event-related business logic.

Detailed introduction to the most comprehensive summary of JavaScript debugging skills

The demo example demonstrates the breakpoint effect when the click event is triggered and when setTimeout is set. The example shows that when the click event breakpoint is selected, the breakpoints are triggered when both buttons are clicked, and when setTimeout is set, the "Set Timer" breakpoint is triggered.

Debugging is a very important link in project development. It can not only help us quickly locate problems, but also save our development time. Being proficient in various debugging methods will definitely bring many benefits to your career development. However, among so many debugging methods, how to choose one that suits your current application scenario requires experience and continuous trial and error accumulation.


The above is the detailed content of Detailed introduction to the most comprehensive summary of JavaScript debugging skills. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template