简体   繁体   中英

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?

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.

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