0

Im using this code to fire a function right after the page is loaded:

function loadpapi(){
    alert("Hello World!");
}

function pctaddLoadEvent(func) {
  var oldonload = document.onload;
  if (typeof document.onload != 'function') {
    document.onload = func;
  } else {
    document.onload = function() {
      if (oldonload) {
        oldonload();
      }
      func();
    }
  }
}

pctaddLoadEvent(loadpapi());

But is starting before the page loads, you can try it here: http://jsfiddle.net/KuTxh/

DomingoSL
  • 14,920
  • 24
  • 99
  • 173

2 Answers2

2
pctaddLoadEvent(loadpapi());

This code calls loadpapi (just like any other function call) and passes the result to pctaddLoadEvent.

You want to pass the function without calling it.

SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964
  • Are you sure?, as far as i can see im passing the function to pctaddLoadEvent – DomingoSL May 13 '13 at 15:02
  • @DomingoSL the `()` after the function name means "call this function here and return the result" – snumpy May 13 '13 at 15:22
  • @DomingoSL No, you are *calling* `loadapi` *immediately* and then passing the *return value* of `loadapi` (which happens to be `undefined`) to `pctaddLoadEvent`. You're passing the result of a function to `pctaddLoadEvent`; instead, you want to pass the function object itself. – apsillers May 13 '13 at 15:23
  • @DomingoSL: How do you think your code is different from code like `displaySomething(getThingy())`? – SLaks May 13 '13 at 15:35
2

I changed the event from document.onload to window.onload: see a discussion here.

This document.onload vs window.onload is a complicated subject. It is likely the document.onload event isn't fired by your browser at all. (Or, as one deals with the window and the other with DOM tree, it is possible that the document.onload event has already fired when your javascript function took action - more testing can confirm that.)

Also, the function passed as parameter goes without the (), as you want to pass the function itself, not its returning value.

function loadpapi(){
    alert("Hello World!");
}


function pctaddLoadEvent(func) {
  var oldonload = window.onload;
  if (typeof window.onload != 'function') {
    window.onload = func;
  } else {
    window.onload = function() {
      if (oldonload) {
        oldonload();
      }
      func();
    }
  }
}

pctaddLoadEvent(loadpapi);

Check demo fiddle: http://jsfiddle.net/st4kQ/

Community
  • 1
  • 1
acdcjunior
  • 132,397
  • 37
  • 331
  • 304