Given the following code, I'm not sure why I can retrieve longAndObscureVariableName but not anotherLongObscureVariableName. Can you explain, and show how I could make anotherLongObscureVariableName accessible from jsFileNumberTwo.js?
Head of HTML document originally contains:
<script type="text/javascript" id="my_globals">
var longAndObscureVariableName = "foo";
</script>
<script type="text/javascript" src="jsFileNumberOne.js" /></script>
<script type="text/javascript" src="jsFileNumberTwo.js" /></script>
Javascript file jsFileNumberOne.js contains this code, which adds another global variable into the #my_globals element:
jQuery(document).ready(function() {
// Store the initial variables, to which we will add more
var initialVars = jQuery('#my_globals').html();
// Define content for script tag:
var scriptContent = initialVars;
// Add to the script content
scriptContent += 'var anotherLongObscureVariableName = "bar";\n';
function insertNewInfo() {
jQuery('#my_globals').html(scriptContent);
};
insertNewInfo();
});
When jsNumberOne.js executes, #my_globals changes to this:
<script type="text/javascript" id="my_globals">
var longAndObscureVariableName = "foo";
var anotherLongAndObscureVariableName = "bar";
</script>
Javascript file jsFileNumberTwo.js contains this code, trying to find out the value of anotherLongAndObscureVariableName:
jQuery(document).ready(function($) {
console.log('longAndObscureVariableName'); // log displays "foo"
console.log('anotherLongAndObscureVariableName'); // log displays "Uncaught ReferenceError: anotherLongAndObscureVariableName is not defined"
console.log('window.anotherLongAndObscureVariableName'); // log displays "undefined"
setTimeout(function(){
console.log(window.anotherLongAndObscureVariableName);
},2000); // log still displays "undefined"
});
I can't retrieve anotherLongAndObscureVariableName from within jsFileNumberTwo.js, even though I thought I was adding it to the global scope by putting it into the head of the HTML document.
Is this a scope issue? Is this a timing/sequencing issue? I think that jsFileNumberTwo.js may be accessing the head content before jsFileNumberOne.js executes, but even with the setTimeout function added I still get "undefined".
What is going on? How can I make this work?