André Hänsel said:
from what I read it seems that the "traditional" way of registering
handlers for DOM events (element.onclick = function() {}) is currently
considered the optimal one.
Hardly, especially not in the case of `onclick'. The `click' event, which
it handles, bubbles, so there is no need to go about the very inefficient
business to add a listener for it to every element in sight, which may never
be touched by the user. Add it to a common parent element instead and
determine the event target. And prefer standards-compliant event methods
over the proprietary `on*' assignments, that is, use a wrapper method to
determine which one is supported first. (You'll need a wrapper for
determining the event target -- Event::target or window.event.srcElement --
anyway, thanks to M$'s unwillingness or incompetence to implement the
standard there.)
But when and where shall I register my handlers?
With a bubbling intrinsic HTML event, such as `click', or a non-bubbling
intrinsic event that is not used on more than, say, a handful of elements,
you should use the corresponding HTML attribute, e.g. `onclick'. With a
non-bubbling intrinsic HTML event that is used on more than a handful of
elements, or a non-HTML event, or a proprietary event, use a wrapper method.
In body onload? In DOMContentLoaded? In a script block at the end of
the page? All three appear quite cumbersome to me. So how should I do
it?
Depends. As a rule of thumb, do not use dynamic assignment of event
listeners, that is, one of the scripting methods describe above, if the
features you are using could work with static assignment as well. Users
will be glad that your document does not work differently (or break) in
different loading states. (That is what the "Unobtrusive JavaScript"
lemmings don't seem to get.)
PointedEars