Home  >  Article  >  Web Front-end  >  Detailed explanation of JS debugging usage

Detailed explanation of JS debugging usage

php中世界最好的语言
php中世界最好的语言Original
2018-04-23 09:23:002571browse

This time I will bring you a detailed explanation of the use of JS debugging, what are the precautions for JS debugging, the following is a practical case, let's take a look.

Just imagine: a certain bug occurs, someone fixes it in a few minutes, and someone spends half a day or a day still unable to find the cause. Would you rather be the former or the latter? If you think you are the former, please read this article carefully. Please note that the article involves many Gif demonstration animations.

Preface: Any programmer must debug the code. Whether you are an expert or a novice, debugging a program is an essential task. Generally speaking, debugging is done after the code is written or when bugs are corrected during the testing period. It is often during the debugging period that it can better reflect the level of the programmer and the accuracy of analyzing the problem. Many beginners always miss the point when looking for the cause of errors, spending a lot of time but unable to solve some bugs that turn out to be quite simple. Mastering various debugging skills will definitely help you 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.

1. Alert, a hard-core debugging master

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 When the page provides very simple accessibility functions. 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 seemed like It looks like this:

It needs to be explained 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.

2. The new generation of debugging king Console

As JS can do more and more things in the Web front-end, its responsibilities are getting bigger and its status is also increasing. 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:

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

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

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.

3. 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 to let the JS execution stop at a specific location to facilitate developers to debug the code segment. analysis and logical processing. In order to be able to observe the effect of breakpoint debugging, we prepare a piece of JS code in advance:

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

3.1. 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 Woolen cloth? 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:

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 the effect after the breakpoint:

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 tool"——" 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:

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 current execution 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 the changes of each of our variables after each line is executed, as shown in the figure below. :

As above, we can see the entire process of variables a and b from the initial value, to adding random values ​​in the middle, to finally calculating the sum and outputting the final result. Completing the question design verification requirements is a piece of cake.

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

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 "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, directly enter the name of the variable 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.

3.2. 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:

4. DOM breakpoint debugging

DOM breakpoint, as the name suggests Add breakpoints on DOM elements for debugging purposes. 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.

4.1. Break on subtree modifications when the internal sub-nodes of the node change

As front-end development becomes more and more complex, front-end JS code becomes more and more complex. The more there are, the more complex the logic becomes. 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:

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.

4.2. 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, the The storage dependence of some data is getting stronger and stronger, and 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:

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.

4.3. Break on node removal

This DOM breakpoint setting is very simple and the triggering method is very clear - when the node when 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:

5, XHR Breakpoints

Front-end development has undergone earth-shaking changes in the past few years. From being unknown at the beginning to being very popular today, Ajax-driven Web rich applications and mobile WebApp single-page applications have become popular. All of this is inseparable from the XMLHttpRequest object, and "XHR Breakpoints" is a breakpoint debugging function designed for asynchronous use.

We can add breakpoint conditions for asynchronous breakpoints through the " " number on the right side of "XHR Breakpoints". When the asynchronous request is triggered, the URL meets this condition, JS logic A breakpoint will be automatically generated. 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.

6. Event Listener Breakpoints

Event listener breakpoints are set according to 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.

DemonstrationExample demonstration shows 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.

I believe you have mastered the method after reading the case in this article. For more exciting information, please pay attention to other related articles on the php Chinese website!

Recommended reading:

js implements front-end and backend transmission of Json

JS sends json format POST request implementation steps

How to use the Post method to pass json parameters

The above is the detailed content of Detailed explanation of JS debugging usage. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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
Previous article:JS usage tips organizedNext article:JS usage tips organized