[javascript] adding to window.onload event?

I'm wondering how to add another method call to the window.onload event once it has already been assigned a method call.

Suppose somewhere in the script I have this assignment...

 window.onload = function(){ some_methods_1() };

and then later on in the script I have this assignment

 window.onload = function(){ some_methods_2() };

As it stands, only some_methods_2 will be called. Is there any way to add to the previous window.onload callback without cancelling some_methods_1 ? (and also without including both some_methods_1() and some_methods_2() in the same function block).

I guess this question is not really about window.onload but a question about javascript in general. I DON'T want to assign something to window.onload in such a way that that if another developer were to work on the script and add a piece of code that also uses window.onload (without looking at my previous code), he would disable my onload event.

I'm also wondering the same thing about

  $(document).ready()

in jquery. How can I add to it without destroying what came before, or what might come after?

This question is related to javascript jquery

The answer is


You can use attachEvent(ie8) and addEventListener instead

addEvent(window, 'load', function(){ some_methods_1() });
addEvent(window, 'load', function(){ some_methods_2() });

function addEvent(element, eventName, fn) {
    if (element.addEventListener)
        element.addEventListener(eventName, fn, false);
    else if (element.attachEvent)
        element.attachEvent('on' + eventName, fn);
}

This might not be a popular option, but sometimes the scripts end up being distributed in various chunks, in that case I've found this to be a quick fix

if(window.onload != null){var f1 = window.onload;}
window.onload=function(){
    //do something

    if(f1!=null){f1();}
}

then somewhere else...

if(window.onload != null){var f2 = window.onload;}
window.onload=function(){
    //do something else

    if(f2!=null){f2();}
}

this will update the onload function and chain as needed


There are basically two ways

  1. store the previous value of window.onload so your code can call a previous handler if present before or after your code executes

  2. using the addEventListener approach (that of course Microsoft doesn't like and requires you to use another different name).

The second method will give you a bit more safety if another script wants to use window.onload and does it without thinking to cooperation but the main assumption for Javascript is that all the scripts will cooperate like you are trying to do.

Note that a bad script that is not designed to work with other unknown scripts will be always able to break a page for example by messing with prototypes, by contaminating the global namespace or by damaging the dom.