JavaScript – When to Bind Event Listeners in jQuery

event-programmingjavascriptjquery

I'm building a medium-sized "single-page" JavaScript application using jQuery. If you include all possible functionality of the application, there are 134 click bindings.

Since most of the content is dynamically loaded, I can't just do this:

$(element).click(function() { ... });

Instead, I'm doing this:

$(document).on('click', selector, function() { ... });

Currently, I'm binding all of these on $(document).ready. But is that bad practice? Is this a speed issue?

The alternative would be to bind the event listeners every time the content is loaded, for example:

$('#content').html(...);
$('#newcontent').click(function() { ... });

The problem with that is it's difficult to organize. What advice can you give me?

Best Answer

You would get a slight increase in performance if you were to bind the events closer to the targets. As it is now every element within the document is being checked to see if it matches "selector". For instance, if your page is organized like this:

<div id="container">
   <div id="content">...</div>
</div>

You would be better off rewriting

$(document).on('click', selector, function() { ... });

as

$("#container").on('click', selector, function() { ... });

You would achieve the same convenience of not having to re-attach the events, but the action events would be limited to "#container". Another thing to consider with attaching events to $(document) is that if new items are added elsewhere on the page with the same selector you won't have to worry about them taking on unwanted behaviors.