views:

34

answers:

2

I'm using a fairly simple system to load javascript dynamically:

include = function (url) {
  var e = document.createElement("script");
  e.src = url;
  e.type="text/javascript";
  document.getElementsByTagName("head")[0].appendChild(e);
};

Let's say I have a file test.js which has the following contents:

var foo = 4;

Now, in my original script, I want to use

include(test.js);
console.log(foo);

However, I get a 'foo has not been defined' error on this. I'm guessing it has to do with the dynamic script being included as the last child of the <head> tag. How can I get this to work?

+3  A: 

That is one problem, but it also takes time for the browser to download and parse the remote JS file — and it hasn't done that before you call console.log.

You need to delay things until the script has loaded.

This is easiest done by letting a library do the heavy lifting, jQuery has a getScript method that lets you pass a callback to run when the script has loaded.

David Dorward
+3  A: 

It is because you have to wait for the script to load. It is not synchronous like you would think. This may work for you:

include = function (url, fn) {
    var e = document.createElement("script");
    e.onload = fn;
    e.src = url;
    e.async=true;
    document.getElementsByTagName("head")[0].appendChild(e);
};

include("test.js",function(){
    console.log(foo);
});
David Murdoch