views:

234

answers:

3

Imagine some code something like this:

  <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
     "http://www.w3.org/TR/html4/loose.dtd"&gt;
  <HTML>
  <HEAD>
  <TITLE>BLAH</TITLE>
  <script language='Javascript' type='text/javascript'>
  var ScriptVersionReqd='1.0';
  </script>

  <script language='JavaScript' type='text/javascript' src='clientscript.js'></script>
  etc. etc.

Does clientscript.js have access to the variable "ScriptVersionReqd"? If not, why not?

+7  A: 

Yes.

As long as the global variable has been put into global scope before it is called by the external script.

Edit in response to a comment: See here for a good explanation of javascript variable scope.

Zack
how do I put the global variable into global scope?
frankster
I had a little bit of redundancy in that sentence. A variable is global if it's put into global scope. A variable is put into global scope either by being initialized outside a function, or being initialized within a function as a non-local variable.
Zack
+1  A: 

Yes. You can see examples of this in things like Google Adsense. With Adsense, you first start by defining the width, colors, etc. Then you include the script which looks for those variables, and determines the output based upon those values.

<script type="text/javascript"><!--
  google_ad_client = "pub-42235573";
  google_ad_slot = "0774868545";
  google_ad_width = 728;
  google_ad_height = 90;
  //-->
</script>
<script type="text/javascript" 
        src="http://pagead2.googlesyndication.com/pagead/show_ads.js"&gt;
</script>
Jonathan Sampson
+1  A: 

Yes, there is no difference for the scope whether the script is included from a file or inline in the script tag.

Guffa