Summary of necessary JS debugging skills and js debugging Summary

Source: Internet
Author: User
Tags chrome developer chrome developer tools

Summary of necessary JS debugging skills and js debugging Summary

Debugging code is indispensable for any programmer, whether you are a master or a cainiao. In general, debugging programs are implemented after code writing or when Bugs are modified during the test period. During code debugging, the level of programmers and the accuracy of problem analysis are better reflected. When looking for the cause of the error, many beginners are always unable to find the cause, and spend a lot of time but cannot solve some bugs that ultimately prove to be quite simple. Mastering all kinds of debugging skills will surely get twice the result with half the effort in your work. For example, you can quickly locate the problem, reduce the fault probability, and help analyze logical errors. Today, Internet front-end development is becoming more and more important. It is especially important to master the front-end development debugging skills to reduce development costs, improve work efficiency, and master the front-end development debugging skills.

This article will explain various front-end JS debugging skills one by one. Maybe you are already familiar with it. Let's take a look at it together. Maybe you have a method you have never seen before. You may wish to study it together, maybe you still don't know how to debug it. Take this opportunity to fill the gaps.

1. Hardcore debugging master Alert

In the era when the Internet is just getting started, the front-end of a webpage mainly displays content, and browser scripts can only provide simple auxiliary functions for pages. At that time, the webpage was mainly running in IE6-based browsers, and the JS debugging function was still very weak. It could only be debugged through the alert method embedded in the Window object. At that time, it should look like this:

It should be noted that the effect shown here is not in IE browser of the current year, but in IE of the later version. In addition, it seems that there is no such advanced console, and alert is also used in real page JS Code. Although alert's debugging method was very primitive, it did have an indelible value at that time. Even today, it has been useful.

2. Next-generation debugging Console

As javascript can do more and more tasks in the front-end of the Web, its responsibilities become greater and greater, and its position becomes more and more important. Traditional alert debugging methods cannot meet various front-end development scenarios. In addition, the debugging information popped up by alert debugging method is not very nice and may block part of the page content, which is somewhat unfriendly.

On the other hand, alert debugging information must be added in the program logic such as "alert (xxxxx)" to work properly, and alert will hinder the continued rendering of the page. This means that after debugging, the developer must manually clear the debugging code, which is a little troublesome.

Therefore, the new generation of browsers Firefox and Chrome, including IE, have successively launched the JS debugging console, supporting the use of similar "console. log (xxxx) "format, print debugging information on the console, without directly affecting the page display. Taking IE as an example, it looks like this:

Okay, goodbye to the ugly alert pop-up box. As a rising star led by Chrome, more functions are provided for the Console:

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

Okay. I have a little extra talk. In short, the appearance of Console and browser built-in Console objects brings great convenience to front-end development and debugging.

Someone may ask, do you need to clear the debugging code after the debugging is complete?

To solve this problem, if you verify the existence of advanced features before using the console object, the business logic will not be damaged if you do not delete it. Of course, to keep the code clean and tidy, try to delete the debugging code irrelevant to the business logic after debugging.

3. JS breakpoint debugging

Breakpoint, one of the functions of the debugger, can interrupt the program in the desired place, so as to facilitate its analysis. You can also set a breakpoint in one debugging. Next time you only need to let the program automatically run to set the breakpoint location, you can interrupt the last breakpoint location, greatly facilitating the operation, it also saves time. -- Baidu encyclopedia

JS breakpoint debugging is to add a breakpoint for the JS Code in the browser developer tool, so that javascript execution can be stopped at a specific location, facilitating the developer's analysis and logic processing of the code segment. To observe the breakpoint debugging effect, we can prepare a JS Code at will:

The code is simple, that is, to define a function, input 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, we can see that the code is running normally through the output result of the console in the test code, but why? Is the final result true because a random number is added to the function? This is meaningless conjecture, but now I want to verify the two numbers passed in by the function, the added random number, and the final sum. What should I do?

Method 1: The most common method mentioned above. Whether using alert or console, we can verify it as follows:

From the discovery, we added three lines of console code in the code to print the data variables we care about, and finally we output the results from the Console panel, we can clearly verify whether the entire computing process is normal and then meet the verification requirements of our questions.

Method 2: There are obvious drawbacks in the verification process of Method 1: A lot of redundant code is added. Next, let's take a look at how to use breakpoint for verification to make it more convenient. Let's first look at how to add a breakpoint, and what is the effect after the breakpoint:

The process for adding a breakpoint to a piece of code is "F12 (Ctrl + Shift + I) open the development tool "--" Click Sources menu "--" find the corresponding file in the left-side Tree "--" click the row number column "to add/delete breakpoints in the current row. After the breakpoint is added, refresh the page and run the JS command to stop the breakpoint. On the Sources page, all the variables and values in the current scope are displayed. You only need to verify each value to complete our question setup verification requirements.

The problem is that when my code is executed to a breakpoint, the values of the variables a and B are displayed after addition, we cannot see the 10 and 20 initially passed in when the sum function is called. So what should we do? This requires you to go back and learn some basic knowledge about breakpoint debugging. After we open the Sources panel, we will actually see the following content on the interface. Let's follow the mouse track to see what it means:

From left to right, each icon represents the following functions:

Pause/Resume script execution: Pause/Resume script execution (the program is executed until the next breakpoint is stopped ).

Step over next function call: call the function that is executed to the next Step (skip 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 (not canceled ).

Pause on exceptions: Automatic breakpoint settings for exceptions.

At this point, the functional keys for breakpoint debugging are almost introduced. Next we can view our program code in a row, and check the changes of each variable after each row is executed, as shown in:

As shown above, we can see that the entire process from the initial value to the center with a random value, and then to the final calculation of the sum and output of the final result, complete the question setup verification requirements.

For the remaining function keys, let's slightly change our test code and use a gif to demonstrate their usage:

Note that the function of printing variable values directly in the code area is newly added in a newer version of Chrome browser. If you are still using an older version of Chrome browser, you may not be able to view the variable information directly when the breakpoint occurs. You can move the mouse over the variable name and pause for a short time to see the variable value. You can also use the mouse to select the variable name and right-click "Add to watch" to view it on the Watch Panel. This method also applies to expressions. In addition, you can switch to the Console panel when a breakpoint occurs, directly enter the variable name on the Console, and press enter to view the variable information. This part is relatively simple. Considering the length issue, it is not used for graphic demonstration.

3.2. Debugger breakpoint

The so-called Debugger breakpoint is actually named by myself, and I don't know what to say about it. Specifically, by adding a "debugger;" Statement to the code, the code will automatically break points when it is executed. The subsequent operations are almost the same as adding breakpoint debugging to the Sources panel. The only difference is that you need to delete the statement after debugging.

Since the method for setting breakpoints is different and the function is the same as that for 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) during development, and this part of JS Code cannot be found in Sources trees, therefore, you cannot directly add breakpoints in development tools. If you want to add breakpoints to the asynchronously loaded scripts, "debugger;" will play a role. We can view the effect of gif images directly:

4. DOM breakpoint debugging

DOM breakpoint, as its name implies, is to add a breakpoint on the DOM element to achieve debugging. In actual use, the breakpoint effect is finally implemented into the JS logic. Let's look at the specific effects of each DOM breakpoint in sequence.

4.1 Break on subtree modifications)

As front-end development becomes more and more complex today, the front-end JS Code is getting more and more complex, and the logic is getting more and more complex. A seemingly simple Web page is usually accompanied by a large section of JS Code, it involves adding, deleting, and modifying DOM nodes. It is inevitable that JavaScript code is difficult to locate code segments, but we can quickly locate related DOM nodes through the Elements Panel of the developer tool, at this time, it is particularly important to use the DOM breakpoint locating script. Let's take a look at the details through the gif Demonstration:

Demonstrate the effect of adding, deleting, and switching sequence operations to the ul subnode (li) to trigger breakpoints. However, modifying the attributes and content of a subnode does not trigger a breakpoint.

4.2. When the node attribute changes, the breakpoint (Break on attributes modifications)

On the other hand, as the business logic of front-end processing becomes more and more complex, the storage dependency on some data is getting stronger, and temporary data is stored in the (custom) attribute of the DOM node, is the preferred method for developers in many cases. Since the HTML5 standard enhanced support for custom attributes (for example, dataset and data-*), more and more attribute setting applications are available. Therefore, the Chrome developer tool also provides support for attribute change breakpoints, the effect is roughly as follows:

This method also requires attention that any operation on the attributes of the subnode will not trigger the breakpoint of the node itself.

4.3 When a node is removed, the breakpoint (Break on node removal)

The DOM breakpoint settings are simple and the trigger method is clear-when the node is deleted. Therefore, this method is usually used when executing the "parentNode. removeChild (childNode)" statement. This method is rarely used.

The debugging methods we introduced earlier are usually used in daily development. when used properly, they can almost deal with almost all the problems in our daily development. However, the developer tool also takes into account more situations and provides more breakpoint methods,

5. XHR Breakpoints

Over the past few years, front-end development has undergone dramatic changes, from the original unknown to the present flourishing moment, Ajax-Driven Web rich applications, and mobile WebApp single-page applications. All of this is inseparable from the XMLHttpRequest object, and "XHR Breakpoints" is a breakpoint debugging function designed for Asynchronization.

We can use the "+" on the right of "XHR Breakpoints" to add a breakpoint condition. When the URL of an asynchronous request is met, the JS logic will automatically generate a breakpoint. The position of the breakpoint is not demonstrated in the demo animation. This is because the demo uses the ajax method encapsulated by jQuery, and the code has been compressed and cannot see any effect, in fact, the XHR breakpoint is generated at "xhr. send () "statement.

XHR breakpoints are powerful in customizing breakpoint rules, which means that we can set breakpoints for a batch, a batch, or even all asynchronous requests. However, it seems that this function is not used much in daily development, at least I do not use much. There are two reasons for this: first, there are not many requirements for breakpoint debugging in daily business; second, most of the current front-end development is based on the JS framework, the most basic jQuery has also well encapsulated Ajax, and few people encapsulate Ajax methods themselves. To reduce the code size, the project usually chooses the compressed code library, this makes XHR resumable tracking less easy.

6. Event Listener Breakpoints

Event listener breakpoint, that is, breakpoint settings based on the event name. When an event is triggered, the breakpoint is directed to the position where the event is bound. The event listener breakpoint lists all page and script events, including mouse, keyboard, animation, timer, and XHR. This greatly reduces the difficulty of debugging the business logic of events.

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

Debugging is a very important part in project development. It not only helps us locate problems quickly, but also saves our development time. Mastering various debugging methods will surely bring many benefits to your career development. However, experience is required to select a suitable debugging method for your current application scenario, you need to keep trying to accumulate.

Here, it can be said that it is a bit of a tip, hope to attract your attention, hope to make you feel a touch, feel a little familiar. I hope you can quickly improve your skills and make yourself a technical expert!

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.