Preface: Debugging code is indispensable for any programmer. Whether you are a master or a novices, debugging programs is an indispensable task. Generally speaking, debugging programs are performed after writing code or when modifying bugs during testing. It is often better to reflect the programmer's level and accuracy of analyzing problems during debugging code. Many beginners are always unaware of the problem when looking for the cause of the error, spending a lot of time but unable to solve some bugs that ultimately prove to be quite simple. Mastering various debugging skills will definitely achieve twice the result with half the effort in work. For example, quickly locate problems, reduce the probability of failure, help analyze logical errors, etc. In today's today when front-end development of the Internet is becoming more and more important, it is particularly important to reduce development costs, improve work efficiency and master front-end development and debugging skills in front-end development.
This article will explain various front-end JS debugging techniques one by one. Maybe you have mastered them, so let's review them together. Maybe there are methods you haven't seen before. You might as well learn them together. Maybe you don't know how to debug. Take this opportunity to fill the gap.
1. Alert, arout debugging master
That was when the Internet was just starting out, and the front-end of the web page was mainly about content display, and browser scripts could only provide very simple auxiliary functions for the page. At that time, web pages were mainly run in browsers dominated by IE6, and the debugging function of JS was still very weak, so they could only be debugged through the alert method built into the Window object. At that time, it should have looked like this:
It should be noted that the effect seen here is not the effect seen in the IE browser back then, but the effect in the higher version of IE. In addition, there seemed to be 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 that time, and even today it has its place to be used.
2. The 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 failed to meet the various scenarios of front-end development. Moreover, the debugging information popped up by the alert debugging method is really not beautiful and will block some page content, which is really not friendly.
On the other hand, the debugging information of alert must be added to the program logic such as "alert(xxxxx)" to work normally, and alert will hinder the continued rendering of the page. This means that after the developer debugging is completed, he must manually clear these debugging codes, which is really troublesome.
Therefore, the new generation of browsers Firefox, Chrome, and 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 without directly affecting the page display. Take IE as an example, it looks like this:
OK, goodbye to the ugly alert pop-up box. The rising star, led by Chrome, has expanded more rich features to Console:
Do you think this is satisfying? The imagination of the Chrome development team is really admirable:
OK, I've said a little bit more off-topic. In short, the emergence of built-in Console objects on the console and browser has brought great convenience to front-end development and debugging.
Some people may ask, does this debugging code need to be cleaned after debugging is completed?
Regarding this issue, if you have advanced existence verification before using the console object, it will not cause damage to the business logic without deletion. Of course, in order to ensure the neat code, after debugging is completed, these debugging codes that are not related to business logic should be deleted as much as possible.
3. JS breakpoint debugging
Breakpoint, one of the functions of the debugger, allows program interrupts to be interrupted where needed, thereby facilitating its analysis. You can also set breakpoints in one debugging. Next time, you only need to let the program automatically run to the set breakpoint position, and you can interrupt it at the last set breakpoint position, which greatly facilitates operation and saves time. --Baidu Encyclopedia
JS breakpoint debugging means adding breakpoints to JS code in browser developer tools, allowing JS execution to stop at a specific location, which facilitates developers to analyze and logical processing of the code segments there. In order to observe the effect of breakpoint debugging, we prepare a piece of JS code in advance:
The code is very simple, it is to define a function, pass in two numbers, add a messy random integer, and then return the sum of the two numbers. Taking Chrome developer tools as an example, let’s take a look at the basic methods of JS breakpoint debugging.
3.1. Sources breakpoint
First of all, in the test code, we can see that the code should be running normally through the output results of the console in the figure above, but why should it be? Because a random number is added to the function, is the final result really correct? This is a meaningless guess, but suppose I'm going to verify now: the two numbers passed in the function, the random number added, and the final sum. So how to operate?
Method 1, the most common one mentioned above, whether using alert or console, we can verify it in this way:
From the figure above, we have added three lines of console code to the code to print the data variables we care about. In the end, we can clearly verify whether the entire calculation process is normal, and then meet the verification requirements set by our question.
Method 2 and Method 1 have obvious disadvantages in the verification process, which is that a lot of redundant code is added. Next, let’s take a look at whether using breakpoints for verification is more convenient. First, see how to add breakpoints and what effect is after the breakpoint:
As shown in the figure, the process of adding breakpoints to a piece of code is to "F12 (Ctrl + Shift + I) Open Development Tools" - "Click Sources menu" - "Find the corresponding file in the left tree" - "Click the row number column" to complete the addition/deletion of breakpoints in the current row. When the breakpoint is added, refresh the page JS execution stops at the breakpoint position. In the Sources interface, you will see all variables and values in the current scope. Just verify each value to complete our verification requirements.
The problem is here. If you are careful, you will find that when my code reaches a breakpoint, the values of the variables a and b displayed have been added. We cannot see the initial 10 and 20 passed in when calling the sum function. So what should I do? This requires you to go back and learn some basic knowledge of breakpoint debugging. After opening the Sources panel, we will actually see the following content in the interface. We follow the mouse track to see what it means:
From left to right, the functions represented by each icon are:
Pause/Resume script execution: Pause/resume script execution (the 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: Break out of current execution function.
Deactive/Active all breakpoints: Turn off/on all breakpoints (not cancelled).
Pause on exceptions: Automatic breakpoint setting for exceptions.
At this point, the function keys for breakpoint debugging have been introduced almost. Next, we can look at our program code line by line to see the changes in each variable after each line is executed, as shown in the figure below:
As mentioned above, we can see the entire process of variables a and b from the initial value, to adding a random value in the middle, and then finally calculating the sum and outputting the final result. It is no problem to complete the verification requirements of the question setting.
For the remaining function keys, we slightly change our test code and use a gif diagram to demonstrate their usage:
One thing to note here is that the function of printing variable values directly in the code area is a new feature added in the newer version of Chrome. If you are still using an older version of Chrome, you may not be able to view variable information directly under breakpoints. At this time, you can move the mouse to the variable name and pause for a short time, and the variable value will appear. You can also select the variable name with the mouse, and 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 at breakpoints, enter the variable name directly in the console, and enter the variable information. This part is relatively simple, considering the length of the article, and not making pictures and demonstrations.
3.2. Debugger breakpoint
The so-called Debugger breakpoint is actually named by me, and I don’t know how to say professional terms. Specifically, by adding a "debugger;" statement to the code, it will automatically break points when the code executes the statement. The next operation is almost exactly the same as adding breakpoint debugging in the Sources panel. The only difference is that the statement needs to be deleted after debugging.
Since the same way of setting breakpoints is different, the function is the same as adding breakpoints to the Sources panel, why does this method still exist? I think the reason should be this: we occasionally encounter asynchronous loading of html fragments (including embedded JS code) in development, and this part of the JS code cannot be found in the Sources tree species, so we cannot directly add breakpoints in the development tool. Then if we want to add breakpoints to the asynchronously loaded script, "debugger;" will work at this time. Let's directly see its effect through the gif diagram:
4. DOM breakpoint debugging
DOM breakpoint, as the name suggests, is to add breakpoints to the DOM element to achieve the purpose of debugging. The effect of using breakpoints in actual use is ultimately implemented in 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 child nodes inside the node change (Break on subtree modifications)
Today, when front-end development is becoming more and more complex, front-end JS code is becoming more and more complex, and a seemingly simple web page is usually accompanied by large segments of JS code, involving many operations of adding, deleting and modifying DOM nodes. It is inevitable that it is difficult to locate code segments directly through JS code, but we can quickly locate relevant DOM nodes through the Elements panel of the developer tool. At this time, it is particularly important to locate scripts through DOM breakpoints. Let's take a look through the gif demonstration:
The above figure demonstrates the effects of adding, deleting and exchanging order operations triggering breakpoints for ul child nodes (li). But it should be noted that modifying attributes and contents of child nodes will not trigger breakpoints.
4.2. Break on attributes modifications
On the other hand, as the business logic of front-end processing becomes more and more complex, the storage dependence on some data is becoming stronger and stronger. storing temporary data in the (custom) properties of the DOM node is a preferred method for developers in many cases. Especially after the HTML5 standard enhances custom attribute support (for example: dataset, data-*, etc.), more and more attribute settings are applied, so Chrome developer tools also provide attribute change breakpoint support, and the effects are 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 is deleted. So usually the case should be when executing the "parentNode.removeChild(childNode)" statement. This method is not used much.
What we introduced earlier is basically the debugging methods we often use in daily development. They can deal with almost all the problems in our daily development when used properly. However, the developer tools also take into account more situations and provide more ways to breakpoint, as shown in the figure:
5. XHR Breakpoints
Front-end development has undergone earth-shaking changes in recent years, from its unknown reputation to its current prosperity, 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 feature designed for asynchronous purposes.
We can add a breakpoint condition to the asynchronous breakpoint through the "+" sign on the right of "XHR Breakpoints". When the URL when the asynchronous request is triggered, the JS logic will automatically generate a breakpoint. The breakpoint position is not demonstrated in the demo animation, because the demo uses the ajax method encapsulated by jQuery. The code has been compressed and there is no effect. In fact, the XHR breakpoint is generated by the "xhr.send()" statement.
The power of XHR breakpoints is that we can customize breakpoint rules, which means that we can set breakpoints for a certain batch, a certain one, and even all asynchronous requests, which is very powerful. However, it seems that this function is not used much in daily development, at least I don't use it much. Think about it, there are roughly two reasons: First, this type of breakpoint debugging requirements are not involved much in daily business; second, most of the front-end development at this stage is based on the JS framework, and the most basic jQuery has also well encapsulated Ajax. Few people encapsulate Ajax methods themselves. In order to reduce the code size, the project usually chooses compressed code bases, making XHR breakpoint tracking relatively less easy.
6. Event Listener Breakpoints
Event listener breakpoint, that is, breakpoint setting is performed according to the event name. When the event is triggered, the breakpoint is 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 business logic in events.
The demo example demonstrates the breakpoint effect when the click event is fired and when setTimeout is set. The example shows that after the click event breakpoint is selected, the breakpoint is triggered when both buttons are clicked, and when setTimeout is set, the "Set Timer" breakpoint is triggered.
Debugging is a very important part of project development. It can not only help us quickly locate problems, but also save us development time. Proficient in various debugging methods will definitely bring many benefits to your career development. However, with so many debugging methods, how to choose a suitable one for your current application scenario requires experience and continuous attempts to accumulate.
Having written this, it can basically be said that it has come out in full swing. I hope it can attract your attention, and I hope it can make you feel a little touched and feel a little familiar. The most important thing is that I hope you can quickly improve your skills and become a skilled person!