views:

428

answers:

1

I am having trouble with some JavaScript running before the page is completely rendered in IE 6 (maybe other versions too but just testing IE6 for now. Firefox seems to be OK). I can get around this by calling the js on window.onload like this:

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

However, my concern is the fact that I will overwrite anything else that may already be in window.onload. The code will be used as part of a library so I can not guarantee that window.onload will not be set somewhere else by someone else. I would rather append my function to the onload event like this:

window.onload += function(){doIt1();}
window.onload += function(){doIt2();}

But when I do so, only doit2() is called. Is there a way to register an event handler for when the page is fully rendered? My second thought would be to just put my code in a loop checking to make sure all my objects exist before running. But I am scared that this could potentially lockup the browser.

Just for some background info, my code is hiding/showing iFrames. I know that I can use the iFrame's onload attribute but I need all of the iFrames to be fully loaded before calling the code.

Any thoughts from the community? Thanks in advance for you input.

+6  A: 

Use this generic addLoadEvent function...

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

    window.onload = function() {
      if(oldLoad) oldLoad();
      func();
    }
  }
}

This essentially queues up functions to be executed. It never overwrites a previously assigned handler. Sample usage below...

addLoadEvent(function() { alert("One!"); });

addLoadEvent(two);
function two() {
  alert("Two!");
}

I want to mention that libraries like jQuery take care of known issues like this for you.

Josh Stodola
Fast response! and pretty much what I was about to put!You might want to put the sample usage into a code block for clarity.It's worth noting that this will always add the new function to the end of the chain being called. This can simply be changed by changing the order of the `func()` and `oldload()` calls in the second part, or possibly by passing a second variable to the function if it needs to be changeable.
PeterJCLaw
+1 Perfect! Damn, I love this site!
J.Hendrix
Yay, this answer put me over 10,000 rep :)
Josh Stodola