Frontend performance optimization: Use event Delegation

Source: Internet
Author: User

Imagine that if you have an unordered list with a bunch of <li> elements, each <li> element triggers an action when you click. At this time, you usually add an event listener to each element. But if this element or the object you added to the listener is frequently removed and added? At this time, you need to handle the removal and addition of event listening when removing the add element. At this time, we need to introduce event delegation.

Event delegation adds an event listener to a parent element instead of an event listener to each child element. When an event is triggered, event.tar get evaluates whether the action needs to be executed. The following is a simple example:

// Obtain the element and add event listening
Document. querySelector ('# parent-list'). addEventListener ('click', function (e ){
// E.tar get is a clicked element!
// If it is a list element
If(e.tar get & e.tar get. tagName = 'lil '){
// We have found this element and can write its operations here.
}
});
The above example is incredibly simple. when an event occurs, it does not poll the parent node to find the matching element or selector, it does not support selector-based queries (for example, using class name or id ). All JavaScript frameworks provide Delegate selector matching. The point is that you do not need to load event listening for every element, but add a event listening to the parent element. This greatly increases efficiency and reduces maintenance!

 

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.