Can't access variables from dynamically loaded javascript

走远了吗. 提交于 2019-12-07 16:07:18

问题


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?


回答1:


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.




回答2:


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);
});


来源:https://stackoverflow.com/questions/2736943/cant-access-variables-from-dynamically-loaded-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!