2

I was just wondering which way is more efficient or if there is any difference in the cost of this operation:

    A) $(document).on('click', '#lol', function(){alert('hello')})

vs

    B) $('#lol').on('click', function(){alert('hello')})

I know the latter won't work if the element with ID 'lol' gets appended to the DOM after the ready function is executed. I've just sort of adopted using implementation A everywhere just as best practice since it keeps all the event code the same regardless of the element I'm targeting. So I'm wondering is there a downside to using option A all the time?

0

2 Answers 2

5

Yes, you shouldn't use document whenever possible and instead use an element that's closer to the target.

From the on() docs (emphasis mine):

Attaching many delegated event handlers near the top of the document tree can degrade performance. Each time the event occurs, jQuery must compare all selectors of all attached events of that type to every element in the path from the event target up to the top of the document. For best performance, attach delegated events at a document location as close as possible to the target elements. Avoid excessive use of document or document.body for delegated events on large documents.

Sign up to request clarification or add additional context in comments.

1 Comment

Congrats on the 100k :)
2

@j08691's answer is perfect in case of one or few elements on page, but if we bind click event to thousands of elements on a page, like all TD elements of a table that has hundreds of rows, then the second option will be slower because jquery is listening to 1000 events at the same time, but the first option only listens to one event and that is the click of the body. Please take a look at benefits of Delegated events in .on() documentation here: http://api.jquery.com/on/

In addition to their ability to handle events on descendant elements not yet created, another advantage of delegated events is their potential for much lower overhead when many elements must be monitored. On a data table with 1,000 rows in its tbody, this example attaches a handler to 1,000 elements:

1 Comment

I'm not advocating not using delegated event syntax. I'm saying that you should select an element closer to the element than document when possible.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.