Can't access variables from dynamically loaded javascript

荒凉一梦 提交于 2019-12-05 18:46:10

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.

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