4

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?

2 Answers 2

5

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);
});
Sign up to request clarification or add additional context in comments.

1 Comment

Nice simple script. But how can we incorporate failure events (like connection not established, or 404 etc) in this..
3

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.