JavaScript: When does JavaScript evaluate a function, onload or when the function is called?

Posted by Benj on Stack Overflow See other posts from Stack Overflow or by Benj
Published on 2010-05-11T16:22:13Z Indexed on 2010/05/11 16:24 UTC
Read the original article Hit count: 172

When does JavaScript evaluate a function? Is it on page load or when the function is called?

The reason why I ask is because I have the following code:

function scriptLoaded() {
   // one of our scripts finished loading, detect which scripts are available:
   var jQuery = window.jQuery;
   var maps = window.google && google.maps;

   if (maps && !requiresGmaps.called) {
     requiresGmaps.called = true;
     requiresGmaps();
   }
   if (jQuery && !requiresJQuery.called) {
     requiresJQuery.called = true;
     requiresJQuery();
   }
   if (maps && jQuery && !requiresBothJQueryGmaps.called) {
     requiresBothJQueryGmaps.called = true;
     requiresBothJQueryGmaps();
   }
}
// asynch download of script
function addScript(url) {
    var script = document.createElement('script');
    script.src = url;
    // older IE...
    script.onreadystatechange=function () {
      if (this.readyState == 'complete') scriptLoaded.call(this);
    }
    script.onload=scriptLoaded;

    document.getElementsByTagName('head')[0].appendChild(script);
}

addScript('http://google.com/gmaps.js');
addScript('http://jquery.com/jquery.js');

// define some function dependecies
function requiresJQuery() { // create JQuery objects }
function requiresGmaps() { // create Google Maps object, etc }
function requiresBothJQueryGmaps() { ... }

What I want to do is perform asynchronous download of my JavaScript and start at the earliest possible time to begin executing those scripts but my code has dependencies on when the scripted have been obviously downloaded and loaded.

When I try the code above, it appears that my browser is still attempting to evaluate code within my require* functions even before those functions have been called. Is this correct? Or am I misunderstanding what's wrong with my code?

© Stack Overflow or respective owner

Related posts about JavaScript

Related posts about jQuery