The necessary JS debugging skills summary _javascript Skills

Source: Internet
Author: User
Tags event listener chrome developer

Preface: Any programmer must go to debug the code, whether you are a master or rookie, debugging procedures are an essential task. Generally speaking, the debugger is to write code or test period to modify the bug, often during the debugging code can more reflect the level of the programmer and analyze the accuracy of the problem. Many beginners find the cause of the error, always to the end, spend a lot of time but can not solve some of the final proof is quite simple bug. Master a variety of debugging skills, will be able to work in a multiplier effect. For example, quickly locating problems, reducing the probability of failure, helping to analyze logic errors, and so on. And in the Internet front-end development more and more important today, how to reduce development costs in front-end development, improve work efficiency, master front-end development debugging skills is particularly important.

This article will explain a variety of front-end JS debugging skills, perhaps you have mastered, that let us to review, perhaps you have not seen the method, may wish to study together, perhaps you do not know how to debug, hurriedly take this opportunity to fill the gap.

1, the Ashes level debugging master Alert

It is still the beginning of the Internet era, the main front page is mainly content display, browser script can only provide a very simple page of the time of the auxiliary function. At that time, the main web page to run in the IE6-oriented browser, JS debugging function is very weak, can only be placed in the Window object in the alert method to debug, at that time it should look like this:

It should be noted that the effect is not seen in the same year's IE browser, but in the high version ie effect. In addition, there seems to be no such advanced console, and alert is used in the real page JS code. Although, alert debugging method is very primitive, but at that time did have its indelible value, even today, already has its application.

2, a new generation of debugging King console

With JS in the Web front-end can do more and more things, more and more responsibilities, and status is more and more important. The traditional alert debugging method has been gradually unable to meet the front-end development of various scenarios. and alert debugging mode pop-up debugging information, that window is really not very beautiful, and will block part of the page content, indeed some unfriendly.

On the other hand, alert's debugging information must be added to the program logic such as "alert (xxxxx)" to work correctly, and alert will prevent the page from continuing rendering. This means that after the developer has finished debugging, you have to manually clear the debug code, which is a bit of a hassle.

Therefore, a new generation of browsers Firefox, Chrome, including IE, have launched a JS debugging console, support the use of similar "Console.log (xxxx)" form, in the console printing debugging information, and does not directly affect the page display. Take IE for example, it looks like this:

Okay, bye. Ugly alert pop-up box. The Up-and-comer, led by Chrome browser, extends richer functionality for the console:

You think that's enough? The imagination of the chrome development team really has to be admired:

Well, a little more to say a little digression. In short, console and browser built-in console objects appear, to the front-end development and debugging has brought great convenience.

Some people will ask, does this debug code need to be cleaned after debugging is done?

On this issue, if the advanced nature of the use of the console object before the existence of validation, the fact that no deletion does not cause disruption to the business logic. Of course, for code to be neat, when debugging is complete, you should remove these debugging code that is not related to the business logic as much as possible.

3, JS Breakpoint debugging

breakpoints, one of the functions of the debugger, allows the program to be interrupted where it is needed, thus facilitating its analysis. You can also set breakpoints in a single debug, the next time you want to automatically run the program to set the breakpoint location, you can set the breakpoint at the location of the last interruption, greatly facilitate the operation, while saving time. --Baidu Encyclopedia

JS breakpoint debugging, that is, in the browser developer tools for JS code to add breakpoints, so that JS execution to a specific location to stop, to facilitate the developer of the Code section of the analysis and logic processing. In order to be able to observe the effect of breakpoint debugging, we prepare a paragraph of JS code in advance:

The code is very simple, that is, to define a function, pass in two numbers, plus a messy random integer, and then return the sum of two numbers. Take the chrome developer tool for example, let's look at the basic method 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, but why should it be? Because the function adds a random number, and the end result is really correct? This is meaningless conjecture, but suppose I am now trying to verify: The two numbers that the function passes in, the random number added, and the final sum. So what's the operation?

Method One, the most common in the past, whether using alert or console, we can verify that:

From the figure above, we have added three lines of console code in our code to print the data variables we care about, and the result of our output from the console panel can clearly verify that the entire calculation process is normal, thus achieving our verification requirements.

Method Two, method one of the validation process there is a clear drawback is that a lot of redundant code added, next we look at using breakpoints to verify that it is more convenient, first look at how to add a breakpoint, and what the effect after the breakpoint:

For example, the process of adding a breakpoint to a piece of code is "F12 (Ctrl + Shift + I) Opens the development tool"--"Click sources Menu"--"find the file in the left tree"--"Click Row Number Column" To complete the Add/Remove breakpoint operation on the current line. When the breakpoint is added, refresh the page JS execution to the breakpoint location stop, in the sources interface will see the current scope of all variables and values, only to verify each value to complete our problem-setting verification requirements.

That's the problem, careful friends will find that when my code executes to a breakpoint, the values shown for the variables A and B are already additive, and we do not see the initial incoming 10 and 20 when the SUM function is invoked. So what should we do? This is going to go back to learning some of the basics of breakpoint debugging. When we open the sources panel, we actually see the following in the interface, and we follow the mouse trajectory to see what it means:

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

Pause/resume Script execution: pause/Resume Scripts Execution (program execution to next breakpoint stop).

Step over next functions call: Performs a function invocation to the next (jumps to the next line).

Step to Next function call: Enter the current function.

Step out of the current function: jumps out of the currently executing function.

Deactive/active All breakpoints: Turn off/Toggle All breakpoints (not canceled).

Pause on Exceptions: Automatic breakpoint settings for exceptions.

To this end, breakpoint debugging function key Introduction is similar, next we can go to the line to see our program code, see each row after execution, we each variable changes, as shown in the following figure:

As above, we can see that a, B variable from the initial value, to the middle plus random value, and then to the final calculation of the total and output the final result of the whole process, complete the problem set verification requirements.

For the rest of the function keys, let's change our test code a little bit, and use a GIF to demonstrate how they use it:

It's important to note that the ability to print variable values directly in the code area is new in newer versions of Chrome, and if you're still using an older version of Chrome, you may not be able to view variable information directly from a breakpoint. At this point you can move your mouse to a short pause on the variable name and the value of the variable appears. You can also use the mouse to select the variable name, and then right-click "Add to watch" in the Watch panel to view it, which is also true for expressions. In addition, you can switch to the console panel in the case of a breakpoint, enter the variable name directly in the console, and return to view the variable information. This section is relatively simple, considering the length of the problem, not to do a diagram demo.

3.2, Debugger Breakpoint

The so-called debugger breakpoint, in fact, I named it myself, professional terminology I do not know how to say. Specifically, by adding the word "debugger" to the code. Statement, the breakpoint is automatically broken when the code executes to the statement. The next operation is almost exactly the same as adding breakpoint debugging in the sources panel, except that the statement needs to be deleted after debugging.

Why does this approach exist in addition to the way the breakpoint is set, and the functionality and the sources panel add a breakpoint effect? I think the reason should be this: we occasionally encountered in the development of asynchronous loading of HTML fragments (including embedded JS code), and this part of the JS code in the sources tree can not be found, so can not directly add breakpoints in the development tool, then if you want to add a breakpoint to the asynchronous loaded script, this time " debugger; " Has a role to play. Let's look at his effect directly through the GIF:

4. Dom Breakpoint Debugging

A DOM breakpoint, as its name implies, adds a breakpoint to the DOM element, which is the goal of debugging. And in the actual use of the effect of the breakpoint is finally landed into the JS logic. Let's look at the concrete effects of each DOM breakpoint in turn.

4.1, when the node inside the child node changes when the breakpoint (break on subtree modifications)

In the front-end development more and more complex today, the front-end JS code more and more complex, a seemingly simple web page, usually accompanied by a large section of the JS code, involving a lot of DOM node increase, delete, change operation. Inevitably encountered directly through the JS code difficult to locate code snippets, but we can through the Developer tool elements panel, quickly navigate to the relevant DOM node, this time through the DOM breakpoint positioning script is particularly important. Specifically, let's take a look at the GIF demo:

The above illustration shows the effect of the addition and deletion of the UL sub Node (LI) and the breakpoint being triggered by the swap order operation. However, it is important to note that property modification and content modification of the child nodes does not trigger the breakpoint.

4.2. Breakpoints when node properties change (break on attributes modifications)

On the other hand, because the business logic of front-end processing is becoming more and more complex, the storage dependence on some data is becoming more and more strong, while storing temporary data in the (custom) attribute of the DOM node is the way that developers prefer to choose in many cases. Especially after the HTML5 standard enhances custom attribute support (for example: DataSet, data-*, and so on), property settings are applied more and more, so the chrome Developer tool also provides attribute-change breakpoint support, which has the following effect:

It is also necessary to note that any action on the properties of the child node does not trigger a breakpoint on the node itself.

4.3. Breakpoint (Break on node removal) when a node is removed

This DOM breakpoint setting is simple, and the trigger is clear--when the node is deleted. So the usual scenario is to use this method when executing the "Parentnode.removechild (childnode)" statement. This method is not used much.

What we have described above is basically the debugging tools that we often use in our day-to-day development, and they can be used to deal with almost every problem in our daily development. However, the developer tool also takes into account more situations and provides more breakpoints, as shown in the figure:

5, XHR breakpoints

In recent years, the front-end development has undergone tremendous changes, from the original obscure to today's flourished, Ajax-driven Web rich applications, Mobile WebApp single page application. All this can not be separated from the XMLHttpRequest object, and "XHR breakpoints" is designed for asynchronous breakpoint debugging function.

We can add the breakpoint condition to the asynchronous breakpoint by "+" on the right side of "XHR breakpoints", when the URL that the asynchronous request triggers satisfies this condition, the JS logic will automatically produce the breakpoint. There is no demonstration of the breakpoint location in the demo animation because the demo is using the jquery encapsulated Ajax method, the code has been compressed to see no effect, and in fact the XHR breakpoint is produced in the "Xhr.send ()" statement.

The powerful part of the XHR breakpoint is the custom breakpoint rule, which means that we can set breakpoints for a batch, one, or even all asynchronous requests, very powerful. However, it seems that this feature is not used in daily development, at least I do not use a lot. Think of the reason for about two points: first, this type of breakpoint debugging requirements in the day-to-day business itself involved not much; second, the current front-end development is mostly based on the JS framework, the most basic jquery has been a good encapsulation of Ajax, very few people themselves encapsulate Ajax methods, and the project to reduce the size of the code , you typically choose a compressed code base, making XHR breakpoint tracking relatively difficult.

6, Event Listener breakpoints

An event listener breakpoint, that is, the breakpoint is set according to the event name. When the event is triggered, the breakpoint to the location of the event binding. Event Listener breakpoint that lists all page and script events, including: mouse, keyboard, animation, timer, XHR, and so on. Greatly reduces the incident aspect business logic debugging difficulty.

The demo example shows the breakpoint effect when the Click event is triggered and when the settimeout is set. Example shows that when the Click event Breakpoint is selected, a breakpoint is triggered when the two buttons are clicked, and the "set Timer" breakpoint is triggered when the settimeout is set.

debugging, is in the project development very important link, not only can help us to quickly locate the problem, but also can save our development time. Proficient in all kinds of debugging means, will be for your career development brings many benefits, but, in so many debugging means, how to choose a suitable for their current application scenarios, which requires experience, need to constantly try to accumulate.

Written here, basically can be said to be out of the whole, hoping to attract your attention, hoping to make you feel a touch, feel some déjà vu. The main thing I still hope you can quickly improve their skills, let yourself become a technical cow!

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: info-contact@alibabacloud.com 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.