I have noticed the use of $(document)
and $('body')
when we want to reference the entire page, especially when binding events.
$(document).on('click', '.myElement', function);
and
$('body').on('click', '.myElement', function);
What is the difference performance-wise? If $(document)
binds the event to the entire HTML document, why do we not use $('body')
to bind events like click
instead?
Note that this question is not referring to the use of the ready function, but the use of .on()
or .delegate()
binding.
The addEventListener() method attaches an event handler to a document.
bind() method is used for attaching an event handler directly to elements. Handlers are attached to the currently selected elements in the jQuery object, so those elements must exist at the point the call to . bind() occurs.
In short: . bind() will only apply to the items you currently have selected in your jQuery object. . live() will apply to all current matching elements, as well as any you might add in the future.
The error() method triggers the error event, or attaches a function to run when an error event occurs.
What is the difference performance-wise?
Almost certainly none, or more accurately, nothing measurable. $('body')
in theory has to search the DOM for the body
element, but that's going to be very fast. Also, since body
is a child of document
, it will be reached in the bubbling of the event nanoseconds before document
is.
There are a couple of differences, though:
If you used $('body')
in a script in the head
and didn't delay execution of it (ready
, etc.), $('body')
wouldn't find anything and wouldn't hook up any handlers. $(document)
, on the other hand, would.
If the body of the document doesn't fill the viewport, then on at least some browsers, you'll get a click on document
but not on body
:
$(document).on("click", function() { $("<p>document</p>").appendTo(document.body); }); $('body').on("click", function() { $("<p>body</p>").appendTo(document.body); });
body { border-bottom: 1px solid #060; }
<p>The line marks the bottom of <code>body</code>. Click above and below the line to see where the click was caught. (Note the line will move as we append to <code>body</code>.)</p> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
Of course, that doesn't apply to your $('body').on('click', '.myElement', function);
because if the click is outside body
, it's not going to pass through a .myElement
...
For global handlers, I use $(document)
, never $('body')
(or $(document.body)
), but that may well be more from habit than reason.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With