views:

50

answers:

2

Some time ago I asked a question about the same issue, @BenAlabaster explained it thoroughly in his answer, I guess I am still missing a piece of logic here.

I tried to call functions that are assigned to variables like I've shown below, in the last function. Well it didn't work. Assuming it happened because the variable functionThree is outside the addOnload() function, I tried to move it inside and the browser just crashed.

addOnload(functionOne);
addOnload(functionTwo);
addOnload(functionThree);

function addOnload(newFunction){
    oldOnload = window.onload;

    if(typeof oldOnload == "function"){
        window.onload = function(){
            if(oldOnload){
                oldOnload();
            }
                newFunction();    //This is what I missed, and that's what caused the crash. 
        }
    }
    else{
        window.onload = newFunction;
    }
}   

function functionOne(){
    alert("This is the first function on this page!");
}

function functionTwo(){
    alert("This is the second function on this page!");
}

functionThree = function(){
    alert("This is the third function on this page!");
}
+3  A: 

This happens because you use functionThree before it is defined.

function x() { 
  // a function that can be used before its declaring block
}

x = function() {
  // a variable that gets assigned a function object when the execution
  // of the program reaches this point, but not before
}

Apart from that, your implementation of addOnload() should go something like this:

function addOnload(newFunction){
  if (typeof window.onloadFunctions === "undefined") {
    window.onloadFunctions = [];
    window.onloadFunctions.push(window.onload);

    window.onload = function() {
      for(var i=0; i<window.onloadFunctions.length; i++) {
        var f = window.onloadFunctions[i];
        if (typeof f === "function") f();
      }
    }
  }
  window.onloadFunctions.push(newFunction);
}   
Tomalak
I just moved the declaration inside and it works.The browser hand because of a different error I made.
Dean
I will check yours too, but the one I posted works fine + it's short.
Dean
+3  A: 

There is a slight issue with your addOnloadFunction: it should be:

function addOnload(newFunction){
    var oldOnload = window.onload;

    if(typeof oldOnload == "function"){
        window.onload = function(){
            newFunction();
            oldOnload();
        }
    }
    else{
        window.onload = newFunction;
    }
}   
Maurice Perry
@Maurice Perry I edited and added the fix, but thanx.
Dean
Your version is still missing the "var" keyword declaring oldOnload as a local variable
Maurice Perry