C graphics
C graphics

Reputation: 7458

How to guarantee a JavaScript file is read before another one

Will this code guarantee the objects.js being loaded prior to tests.js? Say I have objects in objects.js which will be used in tests.js. I just wanna make sure in all browsers objects.js loads before tests.js so that I dont get "Undefined function" run time errors, etc.

Or can you suggest a better approach?

<head>
    <script src="Scripts/objects.js"></script>
    <script src="Scripts/tests.js"></script>
</head>

Upvotes: 1

Views: 95

Answers (3)

bren
bren

Reputation: 4334

Because in most browsers, code is run procedurally, yes, but I would just combine the two files to avoid performance issues

Upvotes: 0

jfriend00
jfriend00

Reputation: 708036

Yes, that will guarantee that objects.js is run before tests.js.

If there are no special attributes on the script tags that affect the loading (such as async or defer), then inline script tags run in the order they appear in the file. That is guaranteed by the specification.

There is a complete description of script loading order including all the special cases of dynamically loaded scripts and defer and async here in this popular answer:

load and execute order of scripts

Upvotes: 2

elclanrs
elclanrs

Reputation: 94131

Scripts are executed synchronously, in the order you declare them, unless you use async attribute.

Upvotes: 2

Related Questions