简体   繁体   中英

When does function order matter?

I understand that JS does a pre-compilation of functions before it executes code. So function order does not matter. But, function order somehow becomes a problem when linking *.js files.

For example,

<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>

In the code above, the function hello2() is defined in a file that is linked after the call is defined. The call fails. So, intuitively I assume now function order does matter in this case.

Considering I perform $(document).ready , the document should be as ready as it gets. So, why does this happen?


As requested, here is the client side HTML

 <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> 

I think the problem is not the order, but that the $(document).ready is executed before the js content is returned, so the function hasn't been loaded yet when it gets called.

The document ready is intended to guarantee the DOM is prepared, not that all the http calls are completed and I'm fairly certain that the usual script blocking doesn't apply in this case.

For what it's worth, I recreated your test and ran it successfully, proving the order doesn't matter and that this is a timing/loading issue: http://havenshade.com/tmp/testalert.html

I didn't find a happy solution though :(

The script tags in the body will likely be executed (or try to be) before the additional requests for the external JS files have completed.

It's less an issue of function declaration order than load order and timing.

您可以使用getScript来获取脚本并在成功回调中执行某些功能,而不是使用脚本标记来导入MyJscript2。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM