Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I attach my .on('click') event to the document or element

Yesterday I was reading the jQuery docs for .on() where was stated:

Avoid excessive use of document or document.body for delegated events on large documents

But today, I was looking at this JSPERF and I notice a better perfomance when the click event is attached to the document.

So right now, i'm confused. The perfomance tests speak against the docs?

like image 281
Gigi2m02 Avatar asked Jul 03 '13 08:07

Gigi2m02


1 Answers

Your JSPerf here is testing the speed to attach events, not the effect that they have on cumulative page performance. This is the wrong thing to test!

Javascript events propagate up the DOM all the way to the document root. This means that if you have an on("click", ...) handler on document, then every click on every element in the document will end up running an event handler, so jQuery can test if its origin matches the delegate target, to see if it should be passed to that event handler.

Imagine that your page has 10 different delegated event handlers on document, all handling various clicks. Every time you click any element in the page, the event will bubble up to the document root, and all 10 of those handlers have to be tested to figure out which (if any) should be run.

In general, you want your delegated events to be as deep in the tree as possible while still enabling your functionality, since this limits the number of elements that may invoke this event, and you can handle the event earlier to prevent it from propagating up the DOM tree.

like image 85
Chris Heald Avatar answered Oct 20 '22 23:10

Chris Heald