Skip to content
Advertisement

Browser-independant workaround for onload event — making sense?

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.

Advertisement

Answer

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().

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement