同步加载和执行javascript代码 [英] Load and execute javascript code SYNCHRONOUSLY
问题描述
有没有办法像同步XMLHttpRequest一样以同步方式加载和执行javascript文件?
Is there a way to load and execute a javascript file in a synchronous way just like a synchronous XMLHttpRequest?
我目前正在使用同步XMLHttpRequest然后eval为此,但调试该代码非常困难......
I'm currently using a sync XMLHttpRequest and then eval for this, but debugging that code is very difficult...
感谢您的帮助!
更新
我现在尝试了这个:
test.html
test.html
<html>
<head>
<script type="text/javascript">
var s = document.createElement("script");
s.setAttribute("src","script.js");
document.head.appendChild(s);
console.log("done");
</script>
</head>
<body>
</body>
</html>
script.js
script.js
console.log("Hi");
输出:
完成
您好
Output: done Hi
所以它没有同步执行。任何想出Hi的想法都会先出现吗?
So it was not executed synchronously. Any idea to make "Hi" appear first?
更新2
其他例子
Update 2 Other example
test.html(脚本标记内的代码)
test.html (code inside a script tag)
var s = document.createElement("script");
s.setAttribute("src","script.js");
document.head.appendChild(s);
SayHi();
script.js
script.js
function SayHi(){
console.log("hi");
}
输出:未捕获的ReferenceError:SayHi未定义
Output: Uncaught ReferenceError: SayHi is not defined
推荐答案
如果你使用它:
function loadScriptSync (src) {
var s = document.createElement('script');
s.src = src;
s.type = "text/javascript";
s.async = false; // <-- this is important
document.getElementsByTagName('head')[0].appendChild(s);
}
你可以做你想做的事情(虽然在一个额外的脚本文件中划分)
You can do what you want (although divided up in an additional script file)
test.html (脚本代码中的代码):
test.html (code inside a script tag):
loadScriptSync("script.js");
loadScriptSync("sayhi.js"); // you have to put the invocation into another script file
script.js :
function SayHi() {
console.log("hi");
}
sayhi.js :
SayHi();
这篇关于同步加载和执行javascript代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!