我正在尝试添加一个脚本元素,其中包含 var myVar = "hello world"
,紧接着我想使用 myVar
。不幸的是,typeof myVar
是未定义
,除非我执行的setTimeout
大于0
。 0
的 setTimeout
不起作用。我复制了 Google Analytic 创建脚本元素的方式,他们似乎工作得很好。我错过了什么吗?
注意:由于某种原因,jsbin 的行为与您将此代码复制/粘贴到 .html 文件并在本地尝试时不同。我认为 jsbin 已经有延迟,这使得 0
的 setTimeout
起作用。
(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/