JavaScript Event Listener and event delegation

Source: Internet
Author: User

Event monitoring and event delegation

In JS, it is commonly used to element.addEventListener() listen to events. However, this approach can have a performance impact when there are a large number of elements in the page that need to bind events. At this point, we can listen to events in the same way as event delegates.

Each event goes through three stages

    • Capture
    • Reach the target
    • Bubble

Event delegates need to use the bubbling of events, bubbling is when the event occurs, the upper layer will receive the event one level at a time.

The following page structure:

<body>   <div id="div1"> <div id="div2"> <button>按钮</button> </div> </div></body>

When the button is clicked, it first receives the event, then bubbles up the layer, then id="div1" receives the event, and then it id="div2" reaches the top of the document.

So you can add an event handler to the parent, which receives the event information for all child nodes. This is the event delegate.

Performance comparison of event listener and event delegation

Compare the performance of event listeners and event delegates by building several button elements and binding event listeners to them.

1. Build several button elements and add them to the body
<! DOCTYPE html><Html><Head><Metacharset="Utf-8" ><Title></Title></Head><BodyId=' Body ' ><ScriptType="Text/javascript" > var BODY =document.getelementbyid ( ' body '); var fragment = document.createdocumentfragment (); for (var i = 0; i < 100; i++) {var btn = document.createelement (  ' btn '; btn.type =  ' button '; btn.innertext =  ' button ' Fragment.appendchild (BTN); } body.appendchild (fragment); </script></ body></HTML>    

At this point, the page generates 100 buttons id for 0 to a class ‘btn‘ . fragment is a document fragment, compared to the advantage of the following code

for(var i = 0;i<100;i++){    var btn=document.createElement(‘button‘); body.appendChild(btn);}

The former page is only re-ranked once, the latter page is re-ranked 100 times, so if you encounter a large module to add DOM, it is best to usefragment

2. Bind the event listener to the button and set the timestamp
    var btn = document.querySelectorAll(‘.btn‘);    var date1 = new Date(); for (var i = 0; i < btn.length; i++) { (function(i) { btn[i].addEventListener(‘click‘, function() { console.log(i); }); })(i) }
3. Bind the Click event to the body to implement the delegate for the event
    var date2 = new Date();    body.addEventListener(‘click‘, function(e) { var element = e.target; if (element.className == ‘btn‘) { console.log(element.id); } }) var date3 = new Date();

Let's analyze the performance of these two approaches with timestamps.

console.log(date2 - date1);console.log(date3 - date1);

By changing the number of buttons, the following data is obtained (in MS):
In 360 compatibility mode:

    • When the number of buttons is 100, the average is 6 0
    • When the number of buttons is 400, the average is 20 0
    • When the number of buttons is 1000, the average is 48 0

Under the new version of Google:

    • When the number of buttons is 1000, the average is 3 0

It can be seen that when there are a large number of elements in the page that require binding events, not all events are triggered, and it is undoubtedly a cost to bind the event handlers to all the elements that need to be listened to, while the event delegate is a good way to resolve performance issues without having to bind event listeners for each element. But write some logic code to determine the source of the event. So, if your Web project is extremely demanding on performance, event delegation will not be an elegant choice.

JavaScript Event Listener and event delegation

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.