KARPACH

WEB DEVELOPER BLOG

How to add additional event handler to window.onload event?

For example, you have the following function:

function InitCustomCode()
{
    // Your custom initialization
}

and you need to run it when the page was loaded.

You can not just write:

<script>
    InitCustomCode();
</script>

because it is going to crash Internet Explorer. So you need to add your function to window.onload event handler. However, window.onload might be already taken by some other function and you don’t have access to this definition. Then you can use the function below to add your handler and maintain the already assigned function.

function addEvent(obj, evType, fn)
{
    if (obj.addEventListener)
    {
        obj.addEventListener(evType, fn, false);
        return true;
    }
    else
    if (obj.attachEvent)
    {
        var r = obj.attachEvent("on" + evType, fn);
        return r;
    }
    else
    {
        return false;
    }
}
Posted on March 21, 2008 by