views:

66

answers:

2

I have recently found myself playing around with events, and as there is no standard for the event indicating that a page has been loaded (like onload vs. pageshow) I wondered whether something speaks against simply putting some javascript at the end of the page. This code would then be executed when the page is loaded.

In this example I would add a keyUp listener to the (input) element identified by iText and assign it to the function updateText(event) (the event object will be passed on to this function).

<html><head></head><body>
<!-- content -->
<script type="text/javascript">
    document.getElementById('iText').onkeyup = updateText;
</script>
</body>
</html>

Sample page here: http://kb.granjow.net/JavaScript/onload.html
Tested in Firefox 3.5, Opera 10.10, IE 6, IE 8, working everywhere.

So, is this good or did I miss something?

Looking forward to your answers. Simon

+2  A: 

That sounds good. There's no reason to not do it that way, as long as your script is at the end of the page. As a matter of fact, ASP.NET uses this method to load it's scripts.

Grinn
Thanks, nice to know! Just had to edit some ASP.NET pages too.
Simon A. Eugster
+2  A: 

This would be fine for basic pages. However, if your script dealt with images that hadn't finished downloading or results from ajax requests you might run into trouble. If you're handcoding things, something like this should work:

function registerEvent(el, event, func, bCapture)
{
    if (el.attachEvent)
        el.attachEvent('on'+event, func);
    else if (el.addEventListener)
        el.addEventListener(event, func, bCapture);

}

Otherwise, the various JS libraries each have their own implementation such as jQuery's $(document).ready().

chprpipr
I should note that as a general rule you should place as much of your javascript at the bottom of the page to improve page rendering times. See Yahoo's YSlow documentation for details and more handy tips (http://developer.yahoo.com/performance/rules.html#js_bottom).
chprpipr
Thank you very much for your answer! Interesting link, too.I've just read a page from ppk about attaching events (to be honest, I was suspicious of not all modern browsers supporting this kind of event registration). He sais that they do, and his article is about 2 years old :) http://www.quirksmode.org/js/events_advanced.html
Simon A. Eugster

related questions