Software Archive
Read-only legacy content
17061 Discussions

Include JavaScript files

Arne_B_1
Beginner
231 Views

Hi there,

I want to include JS-files (locations.js, valves.js) which solely contain the static definition of a large array.
 

I tried it this way:
<script src="js/locations.js"></script>
<script src="js/valves.js"></script>
<script type="application/javascript" src="js/index_user_scripts.js"></script>
<script type="application/javascript" src="xdk/ad/bs_subpage.js"></script>

The content of my array like this:

var valves=[
  {
    "Bestellnummer":"RHW200M1203Y",
    "KVS":"630",
    "Antrieb":6,
    "Ventilart":1,
    "Druckstufe":5
  },
... ];

When I try to access the variable 'valves' in the index_user_script.js I see the warning: 'valves' is not defined. (W117).

As soon as I copy the whole array into the index_user_script.js it works perfectly.

Am I missing something? Does anyone know what the Problem is?

Thanks in advance
Arne

0 Kudos
1 Reply
Chris_P_Intel
Employee
231 Views

Sounds like variable scoping.

When you declare a variable (var valves = ... ) Then it is available in the function that declares it, any any sub-functions declared within that function.  But it is _not_ available to functions outside.

If you declare a variable at the "top level" of a JS file, then it will have global scope and will be available everywhere. This is find for contstants (ie variables that are declared once and do not change), but global variables are not a good general practice - they lead to very difficult to maintain code. So their use should be constrained.

Does that make sense?

 

Also, just FYI. JSHint, which gives warnings about variables not being defined, only knows about the file it is examining. It knows nothing about other files.  If you _know_ that a variable is available globally, you can tell JS Hint that and it will stop warning you.  Put a comment like this at the beginning of your Javascript file:

/*global valves, $, _ */

Note that there is no space between /* and global.   For each word in the list JSHint will no longer warn you about an undefined variable. Of course, you, as the programmer, need to know that the variable is, in fact, global.

 

 

Lastly, if you want to _make_ a variable be global, you can attach it to the window object.  

window.valves = [{a:5}, {a:6}];

and then access it directly elsewhere.

if(valves[0].a == 5){ ....

 

0 Kudos
Reply