有没有办法像同步 XMLHttpRequest 一样以同步方式加载和执行 javascript 文件?
我目前正在使用同步 XMLHttpRequest 然后为此进行评估,但是调试该代码非常困难...
感谢您的帮助!
更新
我现在试过了:
测试.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>
脚本.js
console.log("Hi");
输出: 完毕 嗨
所以没有同步执行。有什么办法让“Hi”先出现吗?
更新 2 其他例子
test.html(脚本标签内的代码)
var s = document.createElement("script");
s.setAttribute("src","script.js");
document.head.appendChild(s);
SayHi();
脚本.js
function SayHi(){
console.log("hi");
}
输出:未捕获的 ReferenceError:未定义 SayHi
最佳答案
如果你使用这个:
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);
}
你可以做你想做的事(虽然在一个额外的脚本文件中分开)
test.html(脚本标签内的代码):
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 - 同步加载和执行javascript代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6074833/