javascript - 如何记录、创建脚本然后立即使用它

标签 javascript asynchronous settimeout

http://jsbin.com/iwuhum/1/

我正在尝试添加一个脚本元素,其中包含 var myVar = "hello world",紧接着我想使用 myVar。不幸的是,typeof myVar未定义,除非我执行的setTimeout 大于00setTimeout 不起作用。我复制了 Google Analytic 创建脚本元素的方式,他们似乎工作得很好。我错过了什么吗?

注意:由于某种原因,jsbin 的行为与您将此代码复制/粘贴到 .html 文件并在本地尝试时不同。我认为 jsbin 已经有延迟,这使得 0setTimeout 起作用。

(function () {
    var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.defer = false;
    ga.src = 'http://bakersdozen13.lfchosting.com/test.js';
    var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})(); // note: the () executes it immediately (or it should!)

$("#out").append('typeof myVar is ' + typeof myVar); // "undefined" :(

setTimeout(function() {
    $("#out").append('<br/>typeof myVar is ' + typeof myVar); // "undefined" :(
}, 0);    

setTimeout(function() {
    $("#out").append('<br/>typeof myVar is ' + typeof myVar); // "string"
}, 1000);

最佳答案

我认为这里的问题是在您第一次调用 typeof 时脚本尚未加载。

您最好使用 onload 或类似的 jquery ready 事件在脚本加载时触发回调。

 ga.onload = function(){
        $("#out").append('typeof myVar is ' + typeof myVar);
    }

为了回应评论,类似以下内容应该可行,但不是一个好主意:

var xhReq = new XMLHttpRequest();
//The false at the end makes the request sychronous
xhReq.open("GET", "http://bakersdozen13.lfchosting.com/test.js", false);
xhReq.send(null);
// I know eval is evil, but this is just a demonstration. This won't happen until the page is loaded.
eval(xhReq.responseText);
// Assuming myVar is a global variable initialized within the script this should now work
$("#out").append('typeof myVar is ' + typeof myVar);

进一步阅读:https://developer.mozilla.org/en-US/docs/DOM/XMLHttpRequest/Synchronous_and_Asynchronous_Requests

关于javascript - 如何记录、创建脚本然后立即使用它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14367799/

相关文章:

Javascript缓存http获取结果

javascript - 每 x 秒多个 XmlHttpRequest

javascript - 在 onClick 上内联encodeURIComponent

ios - 当我扭曲服务时调用 alamofire 异步?

ios - 使用健康数据填充 UITableView?

javascript - 使用 Javascript 打开一个新页面并在那里填充表单值

javascript - 如何编写一个在几秒钟后撤消操作的函数?

javascript - 使用 ionic 应用程序打开网站

javascript - 使 html 输入流

javascript - 如何在 Google Apps 脚本中呈现 Google Pay 按钮