我知道JS在执行代码之前会对函数进行预编译.所以功能顺序无关紧要.但是,在链接*.js文件时,函数顺序会以某种方式成为问题.
例如,
<script src="@Url.Content("~/Scripts/Personal/MyJScript.js")" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function () {
hello();
afterCall();
hello2(); //fails, defined in MyJScript2.js
});
function afterCall() {
alert('inline function defined after call');
}
</script>
<script src="@Url.Content("~/Scripts/Personal/MyJScript2.js")" type="text/javascript"></script>
Run Code Online (Sandbox Code Playgroud)
在上面的代码中,函数hello2()在定义调用后链接的文件中定义.通话失败.所以,我凭直觉认为现在为了功能确实在这种情况下的问题.
考虑到我执行$(document).ready,文档应该尽可能准备好.那么,为什么会这样呢?
<body>
<script src="/Scripts/Personal/MyJScript.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function () {
hello();
afterCall();
hello2(); //fails
});
function afterCall() {
alert('inline function defined after call');
}
</script>
<script src="/Scripts/Personal/MyJScript2.js" type="text/javascript"></script>
</body>
Run Code Online (Sandbox Code Playgroud)
我认为问题不在于顺序,而是 $(document).ready 在 js 内容返回之前执行,因此该函数在调用时尚未加载。
文档就绪的目的是保证 DOM 已准备好,而不是所有 http 调用都已完成,并且我相当确定通常的脚本阻塞在这种情况下不适用。
无论如何,我重新创建了您的测试并成功运行了它,证明顺序并不重要,这是一个计时/加载问题:http ://havenshade.com/tmp/testalert.html
但我没有找到一个满意的解决方案:(