I have two files A.js and B.js. I am importing them in my html as follows
<script type="text/javascript" src="A.js"></script>
<script type="text/javascript" src="B.js"></script>
If I define a variable inside A.js.
- Can I access variable from A in B?
- What is the order of loading? Can B come before?
-
1A Google search and cursory testing would answer both points for you. You can answer 1 by, well, creating the variable and attempting to call it, and you can answer 2 by looking in browser's network console.Mitya– Mitya2017年02月27日 10:42:44 +00:00Commented Feb 27, 2017 at 10:42
-
1@Utkanos, of course I tested, but can I trust that file A is always loaded before?yerassyl– yerassyl2017年02月27日 10:45:12 +00:00Commented Feb 27, 2017 at 10:45
-
well you can define global scope vars outside js files (before loading them) and then interact with them inside files. - It worked for me this way for a client based html game.Adam K.– Adam K.2017年02月27日 10:54:17 +00:00Commented Feb 27, 2017 at 10:54
4 Answers 4
From the HTML spec:
There are three possible modes that can be selected using these attributes. If the async attribute is present, then the script will be executed asynchronously, as soon as it is available. If the async attribute is not present but the defer attribute is present, then the script is executed when the page has finished parsing. If neither attribute is present, then the script is fetched and executed immediately, before the user agent continues parsing the page.
So, as long as you are not using defer or async attributes, A will be available to B.js.
Comments
Yes you can access that variable from B. But in A you won't be able to access variable of B unless it finishes its loading. Loading will maintain sequence A then B. I will prefer if you use jquery and use document.reday function and access variable inside it. This will wait until your all scripts are loaded then it will start execution. A variable out of any function is a global variable in js so you can access it from anywhere you want.
Comments
Javascript is not considered like other programming languages. First of all, they are loaded consecutively and besides, variables in B are not accessible until B locad is completed.
Another words, under the circumstances you are facing, you cannot call anything in B from A until page load is finished or you may use jQuery document ready.
Comments
Use this following,
<script type="text/javascript">
var test = "";
</script>
<script type="text/javascript" src="A.js"></script>
<script type="text/javascript" src="B.js"></script>