Sarge
Sarge

Reputation: 408

Loading order of js files

I have two .js files and they are added in head tag in this order:

<script type="text/javascript" src="script_nr_1.js"></script>
<script type="text/javascript" src="script_nr_2.js"></script>

script_nr_2.js has a variable that uses an object of script_nr_1.js, but when page loads, it first initialize script_nr_2.js's vars. So this causes an error in script_nr_2.js as it tries to init a var with a nonexistent object.

How do I prevent that, and have them be loaded in order?

Upvotes: 3

Views: 4502

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1074028

With that markup, script_nr_1.js will always be run before script_nr_2.js (provided, of course, the first script file is actually accessible). If you're seeing something from the first script that isn't ready yet when the second script runs, that means that the first script is setting up some kind of delayed initialization, perhaps waiting for "DOM ready" or page load.

You'll have to delay the execution of any code in the second script that relies on that initialization until it has been performed. You've said the first script is a library; if it's doing this, presumably it has a means for notifying you when it's done. If it doesn't, I'd look for an alternative library.

Upvotes: 5

Related Questions