views:

28

answers:

1

I want to perform asynchronous JavaScript downloads of two files that have dependencies attached to them.

// asynch download of jquery and gmaps
function addScript(url) {
    var script = document.createElement('script');
    script.src = url;
    document.getElementsByTagName('head')[0].appendChild(script);
}
addScript('http://google.com/gmaps.js');
addScript('http://jquery.com/jquery.js');

// define some function dependecies
function requiresJQuery() { ... }
function requiresGmaps() { ... }
function requiresBothJQueryGmaps() { ... }

// do some work that has no dependencies on either JQuery or Google maps
...

// QUESTION - Pseudo code below
// now call a function that requires Gmaps to be loaded
if (GmapsIsLoaded) { requiresGmaps(); }

// QUESTION - Pseudo code below
// then do something that requires both JQuery & Gmaps (or wait until they are loaded)
if (JQueryAndGmapsIsLoaded) { requiresBothJQueryGmaps(); }

Question: How can I create an event to indicate when:

  • JQuery is loaded?
  • Google Maps is loaded
  • JQuery & Google Maps are both loaded?
A: 

You can attach an event listener to the load event on the <script> elements you created to be informed when the objects have loaded.

This event listener can check to see which scripts are loaded, and call the appropriate functions itself.

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() { ... }
function requiresGmaps() { ... }
function requiresBothJQueryGmaps() { ... }
gnarf
How do I do what you described?
Teddyk
@Teddyk - Added an example
gnarf
That allows for a callback function to happen when just one of the JS files loads. If you'll notice in my original post, I need to initiate a callback when *both* JS are loaded. How do I do that?
Teddyk
The provided code handles that... It just sets the same callback for any script loading, and that callback tests which scripts are available / still need to be initialized.
gnarf