Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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>
like image 568
P.Brian.Mackey Avatar asked Nov 05 '22 11:11

P.Brian.Mackey


2 Answers

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

like image 147
Kato Avatar answered Nov 14 '22 23:11

Kato


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.

like image 42
Dave Newton Avatar answered Nov 15 '22 01:11

Dave Newton