无法从动态加载的javascript中访问变量

Men*_*nno 3 javascript variables loading dynamic

我正在使用一个相当简单的系统来动态加载javascript:

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

假设我有一个test.js文件,其中包含以下内容:

var foo = 4;
Run Code Online (Sandbox Code Playgroud)

现在,在我原来的脚本中,我想使用

include(test.js);
console.log(foo);
Run Code Online (Sandbox Code Playgroud)

但是,我得到了一个'foo尚未定义'的错误.我猜它与包含在<head>标签的最后一个子节点的动态脚本有关.我怎样才能让它发挥作用?

Dav*_*och 5

这是因为你必须等待脚本加载.它不像你想象的那样是同步的.这可能对你有用:

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);
});
Run Code Online (Sandbox Code Playgroud)