JS debugging techniques in front-end development

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

The technique of debugging is an essential skill in any technology development. Master a variety of debugging skills, must be able to work in a multiplier effect. For example, quickly locate problems, reduce the probability of failure, help analyze logic errors, and so on. And in the development of the Internet is more and more important today, how to reduce the development cost in front-end development, improve work efficiency, mastering the 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 together to review, perhaps you have not seen the method, may wish to study together, perhaps you still do not know how to debug, hurriedly take advantage of this opportunity to fill the gap.

Ashes level Debug Master Alert

That is still the beginning of the internet era, the front page is mainly content display, browser script can only provide a very simple accessibility to the page. At that time, the main web page running in the IE6-based browser, JS debugging function is also very weak, can only be built into the window object in the alert method to debug, then it should look like this:


Alert Debug Effect

It is important to note that the effect shown here is not the effect seen in IE in the current year, but the effect in the higher version of IE. In addition, it seems that there is no such a high-level console, and the use of alert is also in the real page JS code. Although the debug mode of alert was primitive, it did have its indelible value, and even today, it has its own application.

New generation of Commissioning King console

With JS in the Web front-end can do more and more, more and more responsibility, and the status is more and more important. The traditional alert debugging method has been 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 obscure part of the content of the page, indeed some not very friendly.

On the other hand, the debug information of alert must add a statement like "" In the program logic to alert(xxxxx) work properly, and alert will prevent the page from continuing rendering. This means that after the developer has debugged, it's a bit of a hassle to manually clear the debug code.

Therefore, the new generation of browsers Firefox, Chrome, including IE, have introduced the JS Debug console, support the use of similar " console.log(xxxx) " in the form of printing debugging information in the console, without directly affecting the page display. In IE, for example, it looks like this:


Console Debug Effect

Okay, bye. Ugly alert pop-up box. And a rising star, led by Chrome, has expanded the functionality of the console:


The more extensive console

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


Fancy Console

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

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

With regard to this issue, if the advanced existence is verified prior to the use of the console object, the business logic will not be destroyed without deleting it. Of course, in order to clean up the code, after debugging is complete, you should delete these business logic-independent debugging code whenever possible.

JS Breakpoint Debugging

breakpoints, one of the debugger's features, allows the program to break where it is needed, thus facilitating its analysis. You can also set breakpoints in a single debug, the next time just let the program automatically run to set the breakpoint location, you can break down the location of the last breakpoint, greatly facilitates the operation, while saving time. --Baidu Encyclopedia

JS breakpoint debugging, that is, in the browser developer tool for the JS code to add breakpoints, so that JS execution to a specific location to stop, convenient for developers to the code snippet analysis and logical processing. In order to be able to observe the effect of breakpoint debugging, we prepared a section of JS code in advance:


Breakpoint Debugging Test Code

The code is simple: Define a function, pass in two numbers, add a random integer, and then return the sum of two numbers. As an example of chrome developer tools, let's take a look at the basic method of JS breakpoint debugging.

Sources Breakpoint

First, the test code in the output of the console we can see that the code should be working properly, but why should it? Because a random number is added to the function, and is the final result really correct? This is meaningless conjecture, but suppose I am now going to verify that the function passed in two numbers, the added random number, and the final sum. So how do we do that?

    • Method One: The most common before, whether using alert or console, we can verify this:

The above verification through the console

From the discovery, we have added three lines of console code in the code to print the data variables we care about, and finally we can verify the whole calculation process is normal by the result of the output from the console panel, so as to achieve the verification requirement of our problem.

    • Method Two: The validation process of method One has obvious drawback is that a lot of redundant code added, next we look at the use of breakpoints to verify, whether more convenient, first see how to add a breakpoint, and after the breakpoint is what effect:

Breakpoint Debugging Effect One

, the process of adding breakpoints to a piece of code is " F12 () Open" "--" "--" Ctrl + Shift + I 开发工具 点击Sources菜单 "-" "that is, to 左侧树中找到相应文件 点击行号列 complete the Add/Remove breakpoint operation on the current line. When the breakpoint is added, the Refresh page JS execution to the breakpoint location stop, in the sources interface will see all the variables and values in the current scope, only need to verify each value to complete our problem set validation requirements.

That's the problem, a careful friend will find that when my code executes to a breakpoint, the variable a and b the value shown are after the addition operation, and we don't see the sum initial incoming sum when the function is called 10 20 . 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 will actually see the following in the interface, we follow the mouse track to see what it means:


Breakpoints Debugging feature Options Introduction

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 the function calls to the next step (jumps to the next line).
    • Step into next functions call: Enter the current function.
    • Step out of current function: Jumps out of the currently executing functions.
    • Deactive/active All breakpoints: Closes/turns on all breakpoints (not canceled).
    • Pause on Exceptions: Exception condition automatic breakpoint setting.

Here, the breakpoint debugging function key introduced almost, then we can go to the line to see our program code, see each line after the completion of the changes in our various variables, as shown in:


breakpoint debugging, line-by-row validation

As above, we can see a , the b variable from the initial value, to the middle of the random value, then to the final calculation of the sum and output the final result of the entire process, complete the problem set validation requirements.

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


Breakpoint entry, jump out function demo

It is important to note that the ability to print variable values directly in the code area is a new feature in the newer version of Chrome, and if you are still using an older version of Chrome, you may not be able to view variable information directly in the case of breakpoints. At this point you can move the mouse over the variable name for a short pause and the variable value will appear. You can also use the mouse to select the variable name, and then right-click Add to watch on the Watch panel to see the same method for the expression. 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 diagram demonstration.

Debugger Breakpoint

The so-called debugger breakpoint, in fact, I gave it a name, the professional terminology I do not know how to say. Specifically, by adding a "" statement to the code debugger; , the breakpoint is automatically executed when the code executes to the statement. The next operation is almost identical to adding breakpoints in the sources panel, the only difference being that the statement needs to be removed after debugging.

Since there are different ways to set breakpoints than to add breakpoints to the sources panel, why do you still have this way? I think the reason is this: we occasionally encountered in the development of the asynchronous loading of HTML fragments (including embedded JS code), and this part of the JS code is not found in the sources tree species, and therefore cannot directly add breakpoints directly in the development tool, if you want to add a breakpoint to the asynchronous loaded script, this time " debugger;"has played a role. Let's look at his effect directly from the GIF:


Debugger breakpoints using demo Dom breakpoint debugging

The DOM breakpoint, as the name implies, is to add a breakpoint on the DOM element to achieve the purpose of debugging. The actual use of breakpoints in the effect of the final landing into the JS logic. Let's look at the specific effect of each DOM breakpoint in turn.

Breakpoint when the node internal child node changes (break on subtree modifications)

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


Breakpoint when a child node has changed

Demonstrates the effect of adding, deleting, and swapping sequential operations on the UL child nodes (LI). However, it is important to note that property modifications and content modifications to the child nodes do not trigger breakpoints.

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 dependency on some data is becoming more and more intense, and storing temporary data in the DOM node's (custom) attribute is a preferred way for developers in many cases. Especially after the HTML5 standard enhanced custom attribute support (e.g. datasets, data-*, etc.), property settings are applied more and more, so the chrome Developer tool also provides attribute change breakpoint support, which works as follows:


Breakpoint Presentation when node properties change

This approach also needs to be noted that any action on the properties of the child node does not trigger a breakpoint on the node itself.

Breakpoint when node is removed (break on node removal)

This DOM breakpoint setting is simple and triggers very clearly-when the node is deleted. So the usual scenario should be to parentNode.removeChild(childNode) use this method when executing the "" statement. This method is not used much.

These are basically the debugging tools we often use in our daily development, and they can be used to almost every problem in our daily development. However, the developer tool also takes into account more situations, providing more breakpoints,


XHR and Event listener breakpoints XHR breakpoints

These years the front-end development has undergone tremendous changes, from the original unknown to today's flourished, Ajax-driven Web-rich applications, mobile webapp single-page application. It's all XMLHttpRequest about the object, and "XHR breakpoints" is a breakpoint-debugging feature designed for Async.


XHR Breakpoints Demo

We can add a breakpoint condition to an asynchronous breakpoint by the "" number on the right side of "XHR breakpoints" + , and the JS logic automatically generates a breakpoint when the URL satisfies this condition when the asynchronous request is triggered. The demo animation does not show the breakpoint location, because the demo uses the jquery encapsulated Ajax method, the code has been compressed to see no effect, and the fact that the XHR breakpoint is generated is the " xhr.send() " statement.

The power of XHR breakpoints is that you can customize breakpoint rules, which means that we can set breakpoints for a batch, one, or all of our asynchronous requests, very powerful. However, it seems that this feature is not used much in daily development, at least I don't use it much. Think of the reason there are about two points: first, this type of breakpoint debugging requirements in the daily business itself involves not much, second, the current front-end development is mostly based on the JS framework, the most basic jquery has been good encapsulation of Ajax, very few people themselves encapsulate the Ajax method, and the project in order to reduce the volume of code , the compressed code base is usually chosen, making XHR breakpoint tracking relatively less easy.

Event Listener Breakpoints

An event listener breakpoint, which is a breakpoint set based on the event name. When the event is triggered, the breakpoint is to the location of the event binding. An event listener breakpoint that lists all page and script events, including: mouse, keyboard, animation, timer, XHR, and so on. It greatly reduces the difficulty of debugging the business logic of the event.


Event Listener Breakpoint Demo

The demo instance demonstrates the breakpoint effect when the Click event is triggered and when settimeout is set. The instance shows that when the Click event Breakpoint is selected, the breakpoint is triggered when the two button is clicked, and when SetTimeout is set, the "set Timer" break point is triggered.

Commissioning, is very important in the development of the project, not only can help us to quickly locate the problem, but also to save our development time. Master a variety of debugging tools, set when for your career development brings many benefits, but, in so many debugging means, how to choose a suitable for their current application scenario, which requires experience, need to constantly try to accumulate.

JS debugging techniques in front-end development

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