Event Binding - jQuery vs Javascript
What are the differences between using
$("#element").click(function() { alert("test"); });
and
<div id="element" onclick="alert('test');"></div>
Is there any difference in performance,开发者_如何学Python functionality or anything else? Should I be using the jQuery way, when I can simply use an onclick
attribute?
jQuery's click
(as well as most of the other libraries' event abstractions) uses standard DOM L2 addEventListener
or MSHTML proprietary (and later copied by some other browsers, like Opera) attachEvent
, when addEventListener
is not available.
If neither addEventListener
, not attachEvent
are present (as is the case with some of the ancient browsers), jQuery does nothing (as of 1.4a2).
onclick="..."
from your second example is what's called an intrinsic event attribute, and is defined in HTML 4.01. The value of such event attribute becomes a function body of an event handler. When event occurs, this handler function is invoked with event
as a first argument; function scope chain is also usually augmented to include some of the element's ancestors and element itself.
The benefits of intrinsic event attribute is wider browser support and arguably better performance. I remember seeing tests of event attributes resulting in a much lesser memory consumption, comparing to those initialized via addEventListener
/attachEvent
. I can't find those tests at the moment.
By avoiding attachEvent
, you also avoid memory leaks in IE, naturally. Most of the popular Javascript libraries actually create circular references in their event abstractions, and are then forced to perform a clean up on page unload in IE. Obviously, these problems disappear when you avoid event abstractions that rely on attachEvent
.
The downsides of event attributes, however, is lack of reusability, breaking separation of concerns and markup pollution (affecting both — size of document, and its maintainability). Remember that logic from event attribute is constantly transferred to a client, instead of being part of external script that's downloaded once and cached. There is also a chance of being tripped on augmented scope.
I would recommend to avoid event attributes, unless absolutely necessary.
Why Inline JavaScript Code Is Such A Bad Thing
and
Unobtrusive JavaScript
It's also always better to use a framework for binding javascript events, since there are cross-browser things you need to take care of yourself if you don't (attachEvent..).
精彩评论