Reputation: 3048
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
.
Upvotes: 1
Views: 77
Reputation: 91
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>
Upvotes: 0
Reputation: 1426
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.
Upvotes: 1
Reputation: 67296
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
.
Upvotes: 3
Reputation: 3248
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.
Upvotes: 1