Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Browser behavior with huge doms

Can anyone speak to how the different browsers handle the following:

Picture an HTML document essentially rendering content of a static app with lots of data.

<div class="abundant_class">
    <div class="abundant_class">
        <div class="abundant_class"></div>
        <div class="abundant_class"></div>
        ...
    </div>       
    <div class="abundant_class">...</div>
    <div class="abundant_class">...</div>
    ...
</div>

Imagine O(1000) such elements in the document.

What's the fastest way to assign a click event to all of these elements?

  • <div class="abundant_class" onclick="javascript:foo()">
  • $('.abundant_class').click(function(foo();));
  • $('div').click(function(){if ($(this).hasClass('abundant_class')){foo();}
  • something else?

I'm wondering specifically how much memory and CPU these choices incur.

Thanks in advance.

Trevor Mills

like image 317
Trevor Mills Avatar asked Jan 27 '26 06:01

Trevor Mills


1 Answers

In cases like this use .live() or .delegate(), where you shift the load from initial binding to event bubbling (which happens anyway), like this:

$('div.abundant_class').live('click', function() {
  foo();
});

This binds one event handler to document and listens for the click event to bubble up and acts upon that, if the element the event bubbled from matches the selector.

As per the comment discussion, here's the very optimized version:

$(document.body).delegate('div.abundant_class', 'click', function() {
  foo();
});
like image 199
Nick Craver Avatar answered Jan 29 '26 20:01

Nick Craver



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!