如何动态加载Javascript文件并立即使用它们?
我正在使用 JQuery 在网页的正文选项卡中动态注入脚本标签。 我得到了类似的信息:
function addJS(url) {
$("body").append('<script type="text/javascript" src='+url+'></script>');
}
我以这种方式添加了几个脚本,然后尝试立即使用它们。 EG :
lib.js
function core() {...}
alert("I'am here !");
init.js
addJS("lib.js");
c = new core();
test.html
<html>
<head>
<title>test</title>
<script type="text/javascript" src="init.js"></script>
</head>
<body>
Hello
</body>
</html>
加载 test.html 会弹出“我在这里”,然后以错误“核心未定义”。 当然,合并这两个 JS 文件将使它们完美地工作。
我只是不明白o_O。
编辑
我简化了这个例子,但杰夫的回答让我明白这是一个错误。 所以这里有一些细节:
当重新加载时,init.js 不在 test.html 的头部,因为我用在书签上执行的代码注入它。
所以真正的执行过程是这样的:
reload test.html > 运行书签> jquery和init.js插入> lib.js 已插入
抱歉造成混淆。
编辑2
现在我有了问题的解决方案(很快:-)),但我仍然对我的问题的答案感兴趣。 为什么会出错?
I am using JQuery to inject dynamically script tags in the body tab of a webpage. I got something like :
function addJS(url) {
$("body").append('<script type="text/javascript" src='+url+'></script>');
}
I add several scripts this way, and try to use them right after. E.G :
lib.js
function core() {...}
alert("I'am here !");
init.js
addJS("lib.js");
c = new core();
test.html
<html>
<head>
<title>test</title>
<script type="text/javascript" src="init.js"></script>
</head>
<body>
Hello
</body>
</html>
Loading test.html pops up "I'm here" and then ends up with an error "core is not defined". Of course merging both of the JS files will make them work perfectly.
I just don't get it o_O.
EDIT
I simplified this example, but Jeff answer made me understand that it was a mistake. So here are some details :
init.js is not in the head of test.html when it reload because I inject it with a code exectuted on a bookmarklet.
So the real execution process is the following :
reload test.html > run the bookmarklet > jquery and init.js are inserted > lib.js is inserted
Sorry for the confusion.
EDIT 2
Now I have the solution to my problem (that was quick :-)) but I am still interested to the answer to my question. Why does this go wrong ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
jQuery 通过 getScript 内置了此功能。
jQuery has this functionality built in with getScript.
您会收到“核心未定义”错误,因为脚本是异步加载的。 这意味着你的浏览器将开始在后台加载lib.js,并继续执行init.js,然后在lib.js加载完成之前遇到“new core()”。
getScript 函数有一个回调,将在脚本加载完成后触发:
You get the "core is not defined" error because the scripts are loaded asynchronous. Which means that your browser will start loading lib.js in the background, and continue executing init.js, and then encounter "new core()" before the lib.js has finished loading.
The getScript function has a callback that will be triggered after the script is finished loading:
请注意,您的 addJS 函数将附加到 body 元素的末尾。
由于浏览器将按照 HTML 源代码中出现的方式运行脚本,因此
将在加载 lib.js 脚本之前运行(在 body 元素的末尾)。
我建议移动 c = new core(); 进入 $(document).ready(function() {...}); 或进入正文标记之后的脚本元素。
Notice your addJS function is appending to the end of the body element.
Since browsers will run scripts as they appear in the HTML source,
will run before your lib.js script is loaded (at the end of the body element).
I would recommend moving c = new core(); into the $(document).ready(function() {...}); or into a script element AFTER the body tag.
IMO,将脚本标签附加到文档末尾来加载脚本是相当难看的。 原因:
适当的方法是使用 $.getScript() ,或者对于更细粒度的控制, fetch带有 $.ajax() 的脚本文件并使用 eval()。
然而,第二种方法有一些问题:如果您在函数内部调用 eval(),那么脚本在函数外部将不可用! 这需要解决方法......
但何苦呢! 使用 $.getScript() 并完成它:)
干杯,jrh。
IMO, appending the script tag to the end of the document to load a script is rather unsightly. Reason:
The appropriate way would be to either use $.getScript(), or for a finer-grained control, fetch the script file with $.ajax() and use eval().
However, the second method has some issues: if you invoked eval() inside a function, then the script won't be available outside it! This mandates workarounds...
but why bother! use $.getScript() and get over with it :)
cheers, jrh.
针对代码失败的原因:向正文添加脚本标记不会阻止进一步的脚本执行。 您的代码添加了它,这将启动浏览器下载过程。 同时,您的脚本尝试调用
core()
,但它不存在,因为lib.js
尚未完成下载。 jQuery 之所以有效,是因为它会等到脚本下载完成后再执行回调函数。In response to why your code is failing: Adding a script tag to the body does not block further script execution. Your code adds it, which starts the browser download process. Meanwhile, your script tries to call
core()
, which doesn't exist becauselib.js
hasn't finished downloading. jQuery works because it waits till the script finishes downloading before executing your callback function.