Skip to content Skip to sidebar Skip to footer

Do Included Javascript Files Have Access To Global Variables In The Parent Document?

Imagine some code something like this:

Solution 1:

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.

Solution 2:

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.

<scripttype="text/javascript"><!--
  google_ad_client = "pub-42235573";
  google_ad_slot = "0774868545";
  google_ad_width = 728;
  google_ad_height = 90;
  //--></script><scripttype="text/javascript"src="http://pagead2.googlesyndication.com/pagead/show_ads.js"></script>

Solution 3:

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

Post a Comment for "Do Included Javascript Files Have Access To Global Variables In The Parent Document?"