Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't access variables from dynamically loaded javascript

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?

like image 541
Menno Avatar asked Oct 24 '25 09:10

Menno


1 Answers

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);
});
like image 62
David Murdoch Avatar answered Oct 26 '25 00:10

David Murdoch



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!