How are inline handlers processed?
I have the suspicion that inline handlers are evalle开发者_如何学Pythond
, but can't find any information on that. Out of curiosity then: does anyone knows how such handlers are processed? For clarity, I mean inline handlers like:
<a href="#" onclick="doSomethingReallyCunning()">...</a>
<input type="checkbox" onmouseover="this.checked=!this.checked;this.blur()"/>
etc.
Internally, inline event attributes are processed by creating an anonymous wrapper function like this:
element.onclick = new Function("event", onclickAttribute);
// etc.
This means that the contents of the attribute are eval
ed but only when the element is inserted into the DOM (after this the function is in a parsed form in memory, just like other event handlers). This means that it will not consume much more memory and time than event handlers assigned in your own, separate JavaScript code. And even if the code had to be parsed every time the event occurs, it wouldn't make such a big difference that a user will notice it.
However, there's a good reason to stay away from using inline event attributes: keeping presentation and logic separate from each other, which improves readability and maintainability. Another advantage is that using minifiers is less painful, as those function names in your JavaScript files may be changed depending on the minifier's settings and intelligence, but not in your markup (a work around to this issue is to use the square bracket notation when defining those functions in your code (like window['doSomethingReallyCunning'] = function (…) {…
), so the function name will be kept intact; however, this is of course not a neat solution if there's a much better one available). If you only assign event handlers in your code by directly referencing functions, all instances of that function's name are changed (of course, the same is true for parameters to setTimeout
and setInterval
).
精彩评论