Click here to Skip to main content
15,921,279 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I want to declare an array in an external file, with extension.js, in such a way that this can be accessed from the main file. Is there a correct way ?

Raymond Mercier
Posted
Comments
RaymondM 10-Jan-12 4:48am    
Thanks for a very thorough answer. I had found some of these websites after a lot of googling, but I was held back by lack of exoperience. In the end I get it to work this way :

In myjs.js :

var Value=[0,1003264,1005824,1038080,.... ];
<nearly 1000="" entries="" in="" value="">
function getvalue(n)
{
return Value[n];
}

In the html file :

<head>
<script scr="myjs.js"> </script>
</head>
.....
<body>
<script scr="myjs.js"> document.write(getvalue(200)); </script>
</body>

I find I need <script scr="myjs.js"> in both head and the body.

Raymond Mercier

1 solution

You can always use multiple JavaScript files in one HTML document using multiple <script> tags; the files are processed in natural order. You only need to take into account the following: the scripts internal to the <head> tag are not executed when the page is loaded, but the scripts internal to the <body> tag are.

The execution of a JavaScript is started from the scripts placed under the <body> tag and any of the event handlers of the element events. At this moment, the code of already loaded scripts can be used.

In this way, none of the files is "external". For JavaScript, the important thing is just the set of declarations in certain order defining the order of execution.

You can define an array in one file, use it in another one. You should understand that the JavaScript arrays are not really the arrays as they are understood in other languages. Rather, all objects (not just arrays, but all objects) are associative containers with elements accessible by any keys which can be used as array indices, with similar syntax. Please see http://www.w3schools.com/js/js_obj_array.asp[^], http://en.wikipedia.org/wiki/JavaScript[^].

In this way, there are no "real" arrays in JavaScript.

For further detail on the order of execution in HTML file, please see:
http://en.wikipedia.org/wiki/JavaScript#Use_in_web_pages[^],
http://en.wikipedia.org/wiki/Unobtrusive_JavaScript[^].

See also questions and discussions on this topic:
http://stackoverflow.com/questions/708449/how-can-i-control-javascript-execution-order[^],
http://stackoverflow.com/questions/6396364/order-of-js-execution-in-html-pages[^],
http://stackoverflow.com/questions/2560025/javascript-execution-order[^],
http://stackoverflow.com/questions/5773976/javascript-jquery-execution-order-question[^].

—SA
 
Share this answer
 
v4

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900