Technical _javascript tips on writing performance-efficient JavaScript events

Source: Internet
Author: User
Tags new set

How to make an efficient Web front-end program is every time I do front-end development will not consciously consider the problem. A few years ago, Yahoo's top-end engineers made a book about improving the performance of the Web front-end, sensational the entire web development technology community, so that the mysterious Web front-end optimization problems become the main street cabbage, Web front-end optimization into a rookie and Daniel can answer simple questions, When the whole industry knows the answer to the blockbuster secret, then the existing optimization technology can not be on your development of the site generated by the quality of the overflight, in order to let us develop the site performance than other people's site better, we need more in-depth independent thinking, reserve more excellent skills.

The event system in JavaScript is the first breakthrough I've ever thought of. Why is it the JavaScript event system? We all know that the Web front-end includes three technologies: how HTML, CSS, and javascript,html and CSS can be combined really at a glance: Style, class, ID, and HTML tags, which is nothing to say, But how does JavaScript get into the middle of HTML and CSS and merge the three? Finally, I found that this pointcut is the JavaScript event system, no matter how much we write the complex JavaScript code, ultimately through the event system embodied in HTML and CSS, so I think that since the event system is the integration of the three-point, then a page, In particular today's increasingly complex web pages are bound to have a large number of event operations, without these events our carefully written JavaScript code only Taeya, Idle heroes:. Now that there are a lot of event functions on the page, is there a problem with efficiency when we write the event function by habit? The answer I've studied is really efficient, and it's a serious problem of efficiency.

To clarify my answer, I'll explain the JavaScript event system in detail.

Event system is JavaScript and HTML and CSS Fusion point of entry, this point is like Java in the main function, all the magic is starting from here, then how the browser to complete this cut? I studied it in a total of 3 ways, and they were:

Mode one: HTML event handling

HTML event processing is to write the event function directly in the HTML tag, because it is tightly coupled with the HTML tag, so it is called HTML event handling. For example, the following code:

Copy Code code as follows:

<input type= "button" id= "btn name=" btn "onclick=" alert (' click me! ') " />

If the Click event function is complex, it is certainly inconvenient to write code, so we often write the function externally, and onclick invokes the function name directly, for example:

Copy Code code as follows:

<input type= "button" id= "btn" name= "btn" onclick= "btnclk ()"/>
function Btnclk () {
Alert ("click me!");
}

The above writing is a very beautiful way of writing, so nowadays still many people will unconsciously use it, but perhaps a lot of people do not know, the latter kind of writing in fact did not have a strong writing, this is also I recently in the study of non-blocking loading script technology encountered problems, because according to the principle of front-end optimization, JavaScript code is often located at the bottom of the page, when the page is blocked by the script, the HTML tag can be referenced in the function may not be executed, this time we click on the page button, the result will be quoted "xxx function undefined error", in JavaScript, such errors are to be try , catch is captured, so in order to make the code more robust, we will have the following rewrite:

Copy Code code as follows:

<input type= "button" id= "btn" name= "btn" onclick= "TRY{BTNCLK ();} catch (e) {} "/>

See the code above is a disgusting can describe.

mode two: DOM0 level event Handling

DOM0-level event handling is the event handling that is supported by all browsers today, and there is no compatibility issue, and seeing such a sentence will make every person who makes the Web front end excited. The rule for DOM0 event handling is that each DOM element has its own event-handling attribute that can assign a function, such as the following code:

Copy Code code as follows:

var btndom = document.getElementById ("btn");
Btndom.onclick = function () {
Alert ("click me!");
}

Event properties for DOM0-level event handling are defined in terms of "on+ event name", with the entire property being lowercase. We know that a DOM element is a JavaScript object in JavaScript code, so it's easy to understand DOM0-level event handling from the JavaScript object's perspective, such as the following code:

Copy Code code as follows:

Btndom.onclick = null;

Then the button click event was canceled.

Then look at the following code:

Copy Code code as follows:

Btndom.onclick = function () {
Alert ("click me!");
}

Btndom.onclick = function () {
Alert ("click me1111!");
}

A later function overwrites the first function.

 Mode three: DOM2 event handling and IE event handling

DOM2 event handling is a standardized event-handling scenario, but IE has a set of features that are similar to DOM2 event handling, but the code is not quite the same.

I have to add some concepts before I explain the way three, otherwise I can't tell the meaning of mode three.

The first concept is: event flow

In page development, we often run into situations where a page's working range in JavaScript can be represented by document, and there's a div,div in the page that covers the document element, and the div has a button element, The button element is covered on the Div, or it's covered on the document, so the problem is, when we click on this button, this click behavior is not just on the button, the div and document are manipulated by clicking, Logically, these three elements can be used to promote the Click event, and the event flow is the concept of the scenario described above, which means that the sequence of events is received from the page.

Second concept: Event bubbling and event capture

Event bubbling is Microsoft's proposed solution to the incident flow problem, and event capture is Netscape's proposed event flow solution, which is as follows:

Bubble event started by Div, followed by the body, and finally document, event capture is the reverse first document, followed by the body, and finally the target element Div, in contrast, Microsoft's program more humane in line with people's operating habits, Netscape's program is very awkward, This is the result of the browser war, Netscape slowed down to solve the problem of the event flow at the expense of user-accustomed code.

Microsoft has designed a new set of event systems in conjunction with bubbling events, and the industry is accustomed to being called IE event handling, ie event handling as shown in the following code:

Copy Code code as follows:

var btndom = document.getElementById ("btn");
Btndom.attachevent ("onclick", function () {
Alert ("click me!");
});

Under IE, adding events through the Attachevent method of DOM elements, and DOM0 event handling, the way to add events is changed from attribute to method, so we add the event to pass parameters to the method, the Attachevent method receives two parameters, the first parameter is the event type, The name of the event type and the event name in the DOM0 event handler, the second argument is the event function, and the advantage of using the method is that if we are adding a click event for the same element, this is as follows:

Copy Code code as follows:

Btndom.attachevent ("onclick", function () {
Alert ("click me!");
});
Btndom.attachevent ("onclick", function () {
Alert ("click Me,too!");
});

Run, two dialog boxes can be normal, so that we can add a number of different click events for DOM elements. What if we don't want an event? What are we going to do, IE provides a detachevent method for deleting events, the argument list is the same as attachevent, if we want to delete a click event, just pass and add the same argument as the event, as shown in the following code:

Copy Code code as follows:

Btndom.detachevent ("onclick", function () {
Alert ("click Me,too!");
});

Run, the consequences are very serious, we are very confused, the second click Incredibly has not been deleted, what is going on? I talked about deleting an event to pass the same parameters as adding an event, but in the JavaScript anonymous function, two anonymous functions are stored internally using different variables, even if the code is exactly the same, and the result is that the phenomenon we see is not able to delete the Click event. So our code has to write this:

Copy Code code as follows:

var ftn = function () {
Alert ("click Me,too!");
};
Btndom.attachevent ("onclick", ftn);
Btndom.detachevent ("onclick", ftn);

The method you add and the way you delete it point to the same object, so the event deletion succeeds. The scene here tells us to write an event to have a good habit of operating functions to be defined independently, not using anonymous functions as a habit.

The next step is DOM2 event handling, which works as shown in the following illustration:

DOM2 is a standardized event that uses the DOM2 event, which begins with the capture method, starting with document, and then to Body,div is a mediation point at which the event is at the target stage, and events begin bubbling after the event enters the target phase. The last event ended on the document. (Capturing the starting point of the event and the end of the bubbling event, I'm pointing to document, where some browsers will start capturing from window, window end bubbling, but I don't think the development time, regardless of how the browser itself is set, is more development-oriented, So I use document all the same here. It is customary to classify the target phase as part of bubbling, mainly because of the more extensive use of bubbling events in development.

DOM2 event processing is very frustrating, every event to promote all elements are traversed two times, this and IE events compared to the performance is much worse, ie only bubble, so ie only need to traverse once, but the traversal is less than the event system for IE more efficient, From the perspective of development design and support of two event systems will give us more flexibility in development, from this point of view DOM2 event is very desirable. The code for the DOM2 event is as follows:

Copy Code code as follows:

var btndom = document.getElementById ("btn");
Btndom.addeventlistener ("click", Function () {
Alert ("click me!");
},false);
var ftn = function () {
Alert ("click Me,too!");
};
Btndom.addeventlistener ("click", Ftn,false);

DOM2 event handling adds an event using a addeventlistener, it receives three parameters than IE event processing more than one, the first two meaning and IE event processing method two parameters, the only difference is that the first parameter to remove on this prefix, the third parameter is a Boolean value, If it evaluates to true, then the event is handled in terms of the capture, which evaluates to false, and the event is bubbling, with a third argument we can understand why the event elements are run two times in DOM2 event processing, in order to be compatible with two event models, but please note here Whether we choose to capture or bubble, two-time traversal is forever, if we choose an event processing, then another event processing process will not promote any event processing function, which is the same as the car hanging empty gear. Through the design of the DOM2 event method, we know that the DOM2 event can only perform one of two types of event handling at run time, it is not possible to two event flow system at the same time, so although the element traversal two times, but the event function can never be sent two times, note that I mean not to promote two times refers to an event function, In fact, we can simulate the case where two event flow models are executed at the same time, such as the following code:

Copy Code code as follows:

Btndom.addeventlistener ("click", Ftn,true);
Btndom.addeventlistener ("click", Ftn,false);

But this type of writing is multiple event processing, which is equivalent to clicking the two times button.

DOM2 also provides a function to delete an event, which is RemoveEventListener, as follows:

Copy Code code as follows:

Btndom.removeeventlistener ("click", Ftn,false);

Using the same as the IE event, the parameters are consistent with the parameters that define the event, but when RemoveEventListener is used, the third parameter does not pass, and the default is to delete the bubbling event, because the third parameter does not pass the default is False, for example:

Copy Code code as follows:

Btndom.addeventlistener ("click", Ftn,true);
Btndom.removeeventlistener ("click", FTN);

Run, found that the event was not deleted successfully.

Finally, I would like to say that the DOM2 event processing in the IE9 including IE9 above the version has been very good support, IE8 the following is not supported DOM2 events.

  Here's a comparison of the three kinds of event patterns, as follows:

  Comparison one: The way one is a party and the other two ways of comparison

The way one is written in HTML and JavaScript together, you have me in me I have you, the way to deepen this is HTML and JavaScript mixed development, in a software term is code coupling, code coupling is not good, and is very bad, this is a rookie programmer's level, So in the end, the other two ways to win.

 Comparison two: Mode Two and way three

Two of them are written in a similar style, sometimes it's hard to say who's good and who's bad, look at the above we found that the most significant difference between mode two and mode three is that the use of 21 DOM elements has one event and only one, while mode three allows a DOM element event to have multiple event handlers, in DOM2 event handling, Mode three also allows us to accurately control the way the event flows, so the mode three function is more powerful than the mode two, so by comparison the way three slightly.

Here is the focus of this article: Event system performance problems, to solve performance problems must find a focus, here I think of the performance of the event system from two points of view, they are: reduce traversal times and memory consumption.

The first is the number of traversal times, whether capturing an event stream or a bubbling event stream, you iterate through the elements, but all the way through the top-level window or document, if the page DOM element is deeply related to the parent-child relationship, the more elements that are traversed, such as DOM2 event handling, the greater the traversal hazard, How do I solve this event flow traversal problem? My answer is no, some of the friends here may have questions, how can there be no? There is an event object in the event system, and this object has a way of preventing bubbling or capturing events, how can I say no? The friend's question makes sense, but if we want to use this method to reduce traversal, then our code will deal with the relationship between the parent-child element, Samson element relationship, if the page elements nested a lot, this is impossible to complete the task, so my answer is not to change the traversal of the problem, can only adapt to it.

It seems that reducing traversal does not solve the problem of event system performance, so it's only a matter of memory consumption. I often hear people say that C # is very good, for Web front-end development It is better to use, we can directly in the C # IDE Drag a button to the page, the button to the page after the JavaScript code will automatically add an event for the button, of course, the event function inside is an empty function, So I think we can put 100 buttons in this way on the page, a code can not have 100 button event processing, super convenient, and finally we have a button to add specific button events, let the page run up, I would like to ask everyone this page efficiency will be high? In JavaScript, each function is an object, each object consumes memory, so this useless 99 event function code must consume a lot of valuable browser memory. Of course we don't do that in a real-world environment. But in today's Ajax popular, single page development crazy popularization of the era, a Web page events are super many, which means that we each event has an event function, but each of our operations will only promote an event, at this time other events are lying down to sleep, Does not work and consumes the computer's memory.

We need a programme to change that, and in reality there is such a scenario. To clearly describe this scenario, I would like to add some background, in the context of DOM2 event processing I mentioned the concept of target object, aside from the DOM2 event processing, in the capture event processing and bubbling event processing also has the concept of target object, the target object is the event specific operation of the DOM element, For example, click the button action button is the target object, regardless of which event processing, event functions will contain an events object, an event object has a property target,target is always point to the target object, the event object also has a property is Currenttarget, This property points to the DOM element that the capture or bubbling event flows to. As we know from the above, the event flow flows to the document, whether it is a capture event or a bubbling event, and if we add a click event on the document, the button on the page does not add a click event, and then we click on the button and we know that the Click event on the document will trigger One of the details here is that when the document click event is being sent, the target of event is a button rather than a document, so we can write code like this:

Copy Code code as follows:

<input type= "button" id= "btn" name= "btn" value= "button"/>
<a href= "#" id= "AA" >aa</a>
Document.addeventlistener ("click", Function (evt) {
var target = Evt.target;
Switch (target.id) {
Case "BTN":
Alert ("button");
Break
Case "AA":
Alert ("a");
Break
}
},false);

Running, we found that the effect was the same as we write button events individually. But its benefits are self-evident, a function to take care of the entire page of the event function, and no event function is idle, simply perfect, this program also has a professional name: Event delegation. The delegate method of jquery is based on this principle. In fact, the efficiency of event delegation is not only reflected in the reduction of the event function, it can also reduce the DOM traversal operations, such as in the above example we add a function on the document, document is the top of the Page object, read it is very efficient, To the specific object events we did not use the DOM to manipulate the target attribute of the event object, all of which can only be summed up in a word: fast, no reason fast.

Event delegates can also bring us a great by-product, friends who have used jquery should have used the live method, the live method is characterized by you can add event operations for page elements, even if this element is not present on the page, you can add its events, understand the event delegation mechanism, The principle of live is very well understood, in fact, jquery Live is through the event commissioned, while live is an efficient way to add events.

Understanding the event delegate, we find that the jquery bind method is inefficient because it uses the original event definition, so bind should be used with caution, but jquery developers are aware of the problem, and the new jquery has an on method, The On method contains all the features of the Bind, live, and delegate methods, so I recommend that the friends who read this article discard the previous way of adding events and add events using the on function.

Event delegation also has the benefit of the example of the event delegate above I'm adding an event to the document, and here I'm going to make a comparison, in jquery we're used to putting the definition of DOM element events in the Ready method, as follows:

Copy Code code as follows:

$ (document). Ready (function () {
Xxx.bind ("click", Function () {});
});

The READY function is executed after the page DOM document is loaded, and it executes before the OnLoad function, which has a lot of benefits, one of the benefits of which is a performance boost, and jquery is a standard practice, and I'm sure some of my friends will have to put some event bindings outside of Ready, The last found button is invalid, this kind of invalid scene sometimes in a moment, after a while, so we often ignore the principle of the problem, not the ready function binding event, this operation is in fact, before the DOM loaded to bind the event, and this time period, it is possible that some elements are not in the page structure, As a result, event bindings can have an invalid condition, so the reason ready defines events is to ensure that when all elements of the page are loaded, the events of the DOM element are defined, but the problem can be avoided when using event delegates, such as binding the event to the document,document representing the entire page. So it is the earliest loading time, so the document on the implementation of event delegation, it is difficult to happen invalid event, it is difficult to happen browser quote "xxx function undefined" problem. To summarize this feature: event delegate code can run at any stage of the page load, which will give developers more freedom to improve web page performance or enhance page effects.

All right, this article is finished. Good night.

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.