68

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?

1
  • 2
    $(document).ready() accumulate. Use it if jQuery's at hand. Commented Mar 22, 2013 at 6:25

5 Answers 5

62

If you are using jQuery, you don't have to do anything special. Handlers added via $(document).ready() don't overwrite each other, but rather execute in turn:

$(document).ready(func1)
...
$(document).ready(func2)

If you are not using jQuery, you could use addEventListener, as demonstrated by Karaxuna, plus attachEvent for IE<9.

Note that onload is not equivalent to $(document).ready() - the former waits for CSS, images... as well, while the latter waits for the DOM tree only. Modern browsers (and IE since IE9) support the DOMContentLoaded event on the document, which corresponds to the jQuery ready event, but IE<9 does not.

if(window.addEventListener){
  window.addEventListener('load', func1)
}else{
  window.attachEvent('onload', func1)
}
...
if(window.addEventListener){
  window.addEventListener('load', func2)
}else{
  window.attachEvent('onload', func2)
}

If neither option is available (for example, you are not dealing with DOM nodes), you can still do this (I am using onload as an example, but other options are available for onload):

var oldOnload1=window.onload;
window.onload=function(){
  oldOnload1 && oldOnload1();
  func1();
}
...
var oldOnload2=window.onload;
window.onload=function(){
  oldOnload2 && oldOnload2();
  func2();
}

or, to avoid polluting the global namespace (and likely encountering namespace collisions), using the import/export IIFE pattern:

window.onload=(function(oldLoad){
  return function(){
    oldLoad && oldLoad();
    func1();
  }
})(window.onload)
...
window.onload=(function(oldLoad){
  return function(){
    oldLoad && oldLoad();
    func2();
  }
})(window.onload)
3
51

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);
}
1
  • so to make it cross-browser compatible, I should use both? Also, if later on in the script I attach a callback to window.onload after previously using addEventListener, does whatever I assigned with addEventListener get cancelled?
    – pepper
    Commented Mar 22, 2013 at 6:43
9

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.

3
  • this is great! what about jquery's $(document).ready() or bind()?
    – pepper
    Commented Mar 22, 2013 at 6:46
  • Do you realize that jquery is just Javascript, don't you? I didn't check but my guess is that it's probably using (2) if available or (1) for older browsers.
    – 6502
    Commented Mar 22, 2013 at 7:48
  • sure of course, I was just asking because $(document).ready() is a bit different from window.onload..."The ready event occurs after the HTML document has been loaded, while the onload event occurs later, when all content (e.g. images) also has been loaded."
    – pepper
    Commented Mar 22, 2013 at 8:54
5

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

5

A pure JavaScript (no jQuery) method that would not override existing onload events but instead add to it, would be:

window.addEventListener('load', function() {
    // do your things here
}

Not the answer you're looking for? Browse other questions tagged or ask your own question.