frankster
frankster

Reputation: 1528

do included javascript files have access to global variables in the parent document?

Imagine some code something like this:

  <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
     "http://www.w3.org/TR/html4/loose.dtd">
  <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?

Upvotes: 2

Views: 2617

Answers (3)

Zack Marrapese
Zack Marrapese

Reputation: 12090

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.

Upvotes: 8

Guffa
Guffa

Reputation: 700592

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

Upvotes: 1

Sampson
Sampson

Reputation: 268424

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">
</script>

Upvotes: 2

Related Questions