2

Is there a difference in loading order between these 2 approaches? Is there a best practice for this?

Approach 1:

HTML

<script src="test.js"></script>
<script>test()</script>

test.js

function test() {
    alert("Hello World!")
}

Approach 2:

HTML

<script src="test.js"></script>

test.js

test()

function test() {
    alert("Hello World!")
}           
4

3 回答 3

0

There is no major difference in performance respect you can choose any if performance is concern.

In first approach if test.js gets failed to load you will get an error method is not defined, while in second approach there will be no error.

So put check whenever you using the function for first approach that whether function is available or not.

or in jQuery you can put all your code in:

$(document).ready(function(){/*do stuff here*/});

it will make sure the javascript is loaded and the DOM is ready.

于 2013-09-08T18:07:19.063 回答
0

They both doing same thing; setting window.test to a function and executing that. In approach 1, since a browser execute scripts sequencially, when test() is called, test will be defined. In approach 2, since test is bound before the code is executed, test() will be succeed.

I will prefer approach 2 over approach 1, since I can know where test is defined when calling test, and all JS code is in a separated file, not directly in an HTML file.

于 2013-09-08T18:17:31.960 回答
-1

No, they both are equal. Use any of them.

于 2013-09-08T18:03:01.957 回答