JavaScript onload

Here’s a way to use window.onload that won’t break other scripts that also need to use it: Store the current value of window.onload before you set the new value, then call it as part of your own initialization.

I’ve written this short helper function to do the job for you:

  function WindowOnload(f) {
    var prev=window.onload;
    window.onload=function(){ if(prev)prev(); f(); }
  }

Here’s an example of how to use it:

Replace this:with this:
  function my_init() {
    . . .
  }
  window.onload = my_init;
  function my_init() {
    . . .
  }
  WindowOnload( my_init );

How does it work?

Each time you call WindowOnload() the current value of window.onload is stored in the local variable prev. It is then replaced by a function that calls prev() and then calls your initialisation function f(). Each call to WindowOnload() creates a new version of the prev local variable, so you get a chain of initialization functions that call each other in the correct order.

The first time WindowOnload() is called, window.onload may be null, so the init function checks that prev has a value before trying to call it as a function. This check is only really needed by Internet Explorer.

Why is this better?

This approach works correctly with all other scripts that want to use window.onload, no matter how they are written. There are initialization schemes that store init functions in an array, and then call them all in a loop, but they rely on all of the JavaScript on the page using the correct registration function. Just one script that doesn’t play along will break everything else.

The WindowOnload() function works independently, but does not break other initialisation schemes.

(The WindowOnload() function is hereby assigned into the public domain.)

Comment · RSS · TrackBack

  1. ArdentRogue said,

    29 July, 2005 @ 18:04

    Thanks for sharing. I was looking for some ‘onload’ help, and found this method helpful

  2. Evan said,

    29 November, 2005 @ 21:38

    AS did I. Thanks.

  3. anders dahl said,

    14 March, 2006 @ 15:55

    Sweet, tanx. Does the trick…

  4. Adam Hamilton said,

    3 May, 2006 @ 18:26

    This function can cause “F is not a function” errors in FireFox, and can cause a non-fatal page load error in IE, causing the error symbol in the bottom corner. The fix is to remove the () after f, so you just have:

    window.onload=function(){ if(prev)prev(); f; }

    This works the same, but does not confuse the browser’s poor (non-standards-compliant) parser.

    The function works great though, I wouldn’t have thought you could do that. Thanks for your help!

  5. Tek Boy said,

    24 August, 2006 @ 15:13

    Adam Hamilton –

    Maybe that was in an older version of Firefox? I’m using v1.5.0.6, and using the equivalent of f() works fine for me. Here’s my code:

    function WindowOnload(oNewOnloadFunction) {
        var oPreviousOnloadFunction = window.onload;
        window.onload = function() { 
            if (oPreviousOnloadFunction) { oPreviousOnloadFunction(); }
            oNewOnloadFunction();
        }
    }
    
    function myInitFunction() { 
        alert('testing'); 
    }
    
    WindowOnload(myInitFunction);
    

    -= Tek Boy=-

  6. Maria said,

    11 October, 2006 @ 13:31

    Great, thanks! Just what i was looking for.

  7. Patrick FIsher said,

    26 November, 2006 @ 07:46

    Readers should know of Simon Willison’s analogous function, addLoadEvent, which may be more robust.

    // simon.incutio.com/archive/2004/05/26/addLoadEvent (updated for IE 7, 2006-05-28) function addLoadEvent(func) { var oldonload = window.onload; if (typeof window.onload != 'function') { window.onload = func; } else { window.onload = function() { if (oldonload) { oldonload(); } func(); } } }

  8. BlackShadow said,

    26 November, 2006 @ 13:19

    Is there a way you can use parameters

    WindowOnload(myInitFunction(param)); Doesn’t work.

  9. Ryan said,

    29 November, 2006 @ 13:47

    How about a function for removing a specific function call from an existing event.

    I can convert the event (windows.onload) to a string and then manipulate the string, but how can I re-attach the string as an event again…

    Or is there a better way of detecting a function call in an event and then targeting it for removal?

    I realise I can simply remove all function calls from an event, but I’d prefer to remove the specific function call.

    Thanks, Ryan

  10. Oliver said,

    19 December, 2006 @ 16:45

    @Blackshadow

    To call a function with a parameters, wrap the call in another function that doesn’t take parameters:

    WindowOnload(function() { myInitFunction(param) });

  11. Adam Hamilton said,

    2 January, 2007 @ 03:16

    I finally nailed down that “F is not a function” error yesterday – my script dynamically added 0 to n functions to WindowOnload, and having 0 functions added resulted in f being null. Thus, f() is not valid, because a null function cannot be called. However, using f (no parenthesis), we get the same result if f is not null; if f is null, this statement evaluates to ‘null;’, which is also valid. So removing the parenthesis should make the function more robust, although they are not technically an error.

  12. Dave said,

    10 January, 2007 @ 18:16

    Thanks so much. I’m using Event Calendar inside an onLoad collapsible menu, and I couldn’t figure out why the “Prev” and “Next” links weren’t dynamic until you explained it on the Event Calendar blog. Using this fix, it works like a charm….I really appreciate it!!

  13. Dag Sverre said,

    30 January, 2007 @ 11:45

    Re paranthesis on f: I believe strongly it is bad to make “function behave more robust” against user error. Fail early and fail violently, that’s the best way to avoid bugs. If you are actually calling this things with a null parameter then you probably have a bug somewhere else in your script!

    If anything, add a check at the top: if (typeof(f) != ‘function’) throw “f cannot be null”;

    BTW, standard-compliant etc. way of doing this is using window.addEventListener, which doesn’t replace the original event handler. However IE doesn’t support it (but has an attachEvent which might work the same, not sure).

  14. Steve said,

    31 January, 2007 @ 17:38

    Works for me! Thanks for the help!

  15. Brandon said,

    27 February, 2007 @ 21:54

    Exactly what I was looking for, and it works like a charm! Thanks a ton.

  16. Optimus Pete » Blog Archive » JS: Execute JavaScript on Page Load said,

    14 May, 2007 @ 10:46

    [...] I originally saw this technique here. Alternative JS initialisation scripts are available but so far this one has worked well for me, so I’ll be sticking with it. [...]

  17. mohan said,

    9 June, 2007 @ 22:17

    I want to keep a header java script in a separate file and have this script loaded to different pages when the page opens, How do I do that? Thanks Mohan

  18. Torstens Blog » Problem mit onload.window bei EventCalendar3 und SimpleTags said,

    18 October, 2007 @ 11:55

    [...] Um die Probleme zu beheben, hat die Autorin des EventCalendar eine kleine Anleitung geschrieben, wie die Autoren anderer Plugins dieses Problem beheben können. Da ich aber nicht die Geduld hatte, auf eine entsprechende Antwort im Wordpress-Deutschland Forum zu warten, habe ich mich trotz mangelnder JavaScript-Kenntnisse an das Problem gewagt und sogar geschafft, dieses auch zu beseitigen. Die überarbeiteten Dateien könnt Ihr hier von mir downloaden: angepasste Datein für das SimpleTags-Plugin. [...]

  19. Nigel Burrell said,

    8 June, 2009 @ 19:40

    Thanks so much for the Javascript onload solution.

  20. Nilson Chagas said,

    14 July, 2009 @ 14:13

    I have the problem when click [ + ], but I desabled all plugins, after enabled first Event-Calendar, Event Calendar Widget, and another plugins.

    So, no more problem.

  21. Nilson Chagas said,

    14 July, 2009 @ 17:39

    The click [+] dont work if plugin Post Excerpt active.

  22. Naveen said,

    10 August, 2011 @ 09:39

    Vary vary nice code

Leave a Comment

Sponsors