Event Delegation Performance in Javascript

119 Views Asked by At

I have read about event delegation concept in Javascript. Instead of attaching event to every child node we can bind event to the parent. I tried to measure the timings in traditional and delegated scenario.

With Delegation

Traditional

HTML

<ul id="list">
    <li id="1">Item #1</li>
    <li id="2">Item #2</li>
    <li id="3">Item #3</li>
    <li id="4">Item #4</li>
    <li id="5">Item #5</li>
    <li id="6">Item #6</li>
    <li id="7">Item #7</li>        
    <li id="8">Item #8</li>
</ul>

Delegation

document.getElementById('list').addEventListener('click', function(e){
    var T1 = window.performance.now();
    console.log(window.performance.now()-T1);
});

Traditional

document.getElementById('1').addEventListener('click',function(){
    var T1 = window.performance.now();
    console.log(window.performance.now()-T1);
});
document.getElementById('2').addEventListener('click',function(){
    var T1 = window.performance.now();
    console.log(window.performance.now()-T1);
});

The timing for listening an event in case of delegation is higher compared to the case where an event is directly binded to the child node. See the console for results. The reason for this which I thought is that the event bubbles and reaches the parent node and takes time compared to where it is captured at the child node directly.

Am I correct? Delegation is laggy? Low bandwidth users will have a bad UX?

0

There are 0 best solutions below