如果one.js碰巧在two.js被解析之前完成加载,x会存在吗?当然这是可能的,因为一旦加载异步脚本,它就会立即执行并阻止进一步解析 HTML 文件。从而在定义 x 之前阻止 two.js。
据我所知,JavaScript 不需要解析函数内的变量。相反,它会等到函数执行后才确定其存在。由于 x.prt 直到窗口及其资源(包括 two.js)加载后才使用,因此异步加载两个脚本应该是安全的,对吗?
jsfiles.html:
...
<script src="lib/one.js" type="text/javascript" async="async"></script>
<script src="lib/two.js" type="text/javascript" async="async"></script>
...
one.js:
window.addEventListener("load", function() {
x.prt("Will this print 100% of the time?");
}, false);
two.js
var x = {
prt: function(str) {
console.log(str + " Or will this definition not be seen?");
}
};
最佳答案
在函数执行之前,JavaScript 不会尝试计算函数内部的任何内容。在函数执行之前,它不会尝试查找 x
,此时 x
将作为全局变量存在。
If one.js happens to finish loading before two.js even gets parsed, will x exist?
不,但这并不重要,因为您不需要存在 x
来定义使用 x
的函数。 x
将在窗口的加载回调触发并且回调尝试使用 x
时存在。
关于javascript - javascript 在执行之前会解析函数定义中的变量吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31687661/