Why not use Javascript handlers on the body element?
Using onLoad
is becoming less and less common because callbacks can't be stacked using this method, i.e. new onload
definitions override the old ones.
In modern frameworks like jQuery and its .load()
, callbacks can be stacked and there are no conflicts when using different scripts, plugins, etc. on the same page.
Also, it is widely regarded good practice to keep the markup separate from the code, so even if one would want to use onload
(which is perfectly okay if you control the complete environment and know what you're doing) one would attach that event on the scripting side either in the head
or a separate javaScript file:
window.onload = function() { document.getElementById...... }
There's nothing wrong with using the onload
attribute in the <body>
element, provided:
- you have complete control of the page
- no other script that you use on the page currently or could have in the future will try and set an
onload
handler on the body element or thewindow
object - you know your own mind and are happy to have a small piece of script in your mark-up.
It's also worth noting that <body onload="...">
is a part of a formal standard (HTML 4) while window.onload
is not, although it is implemented in all the major browsers going back many years.
Disregarding the issues of whether inline event handler attributes are a wrongness for a moment, the onload
event is a poor place to put an autofocuser, since it only fires when the whole page is loaded, including images.
This means the user will have to wait longer for the autofocus to occur, and if the page takes quite a while to load they may already have focused elsewhere on the browser page (or chrome, such as the address bar), only to find their focus stolen halfway through typing. This is highly irritating.
Autofocus is a potentially-hostile feature that should be used sparingly and politely. Part of that is reducing the delay before focusing, and the easiest way to do that is a script block directly after the element itself.
<input id="x">
<script type="text/javascript">
document.getElementById('x').focus();
</script>