Be Excellent to Other Onload Events

Tags: JavaScript, HTML

I've noticed a disturbing trend lately with regards to the onload event of an HTML page. This trend includes one developer overwriting the onload event with their own function. I've seen some web pages that have this for the body tag:

<body onload="myLoadFunction();">

And because this doesn't seem to work for them they put this right before the closing body tag:

<script type="text/javascript">
    myLoadFunction();
</script>
</body>

They do this without first finding out why the onload doesn't work. The issue is that in one of the many script libraries that they've included in their document is a function that destructively adds its own onload function into the DOM.

In a JavaScript book that I read a while ago the author included this code for adding an onload function in a non-destructive way:

function addLoadEvent(func)
{
    var oldonload = window.onload;
    if (typeof window.onload != 'function')
    {
        window.onload = func;
    }
    else
    {
        window.onload =
            function()
            {
                oldonload();
                func();
            };
    }
}

To use this after your function that you want to add to the onload event just call:

addLoadEvent(myFuncName);

I believe I got this function from the O'Reilly book "JavaScript: The Definitive Guide" by David Flanagan.

If you are using the Prototype framework you can just use the observe method on the Event object to do this. More information can be found here.

Add a Comment