I have a site full of AJAX so I need to delegate methods to document clicks, assuming I have jQuery library too.
I just want to know what's more efficient between these two codes:
$(document).on('click', '.delegate1', function(){
doSomethingForDelegate1();
}).on('click', '.delegate2', function(){
doSomethingForDelegate2();
});
Or:
$(document).on('click', function(event){
var element = $(event.target);
if(element.hasClass('delegate1')){
doSomethingForDelegate1();
} else if(element.hasClass('delegate2')){
doSomethingForDelegate2();
}
})
I want to implement the code that will have less impact on client's execution time and therefore have a faster site. I know that maybe the difference won't be much but it's always better to work faster ;)
If there's a method that's faster than these 2 methods it's welcome too. Thanks.
If the difference isn't noticeable enough then I want to know what algorythm is cleaner, binding an event for each delegate or bind a single event and compare classes.
The 2nd method can be efficient when there are many elements that are being added to the DOM at a later time. SO attaching a single event to the document and delegating can really speed up the application .
But if the number of elements created and needed to be attached are not huge, both should perform at the same rate..
I would go with the 1st approach as it is lot more cleaner.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.