Reputation: 96835
This is the basis of how my document is written out. I have an external JavaScript file positioned at the top of the head element. Below it, I have code the references content from it. I would expect since the code is below the file it would work but it doesn't. It only works if I wrap the code in a window.onload()
function. Or if I put the code in a script in the body element.
<html>
<head>
<script type="text/javascript" src="myJavaScript.js"></script>
<script type="text/javascript">
console.log(w); // w is a variable inside myJavaScript.js but throws an error stating "w is not defined".
</script>
</head>
<body></body>
</html>
Why does this code behave this way? I have the file written on top of the code that calls content within it yet it still doesn't work.
EDIT: I found the error and it was that I wasn't defining the code in myJavaScript.js in the global scope. That's why the variable w never got through.
Upvotes: 0
Views: 121
Reputation: 707696
You'd have to show us the relevant code in myJavaScript.js
for us to know what's really going on, but it's fairly clear that either w
isn't defined at the global scope in myJavasScript.js
or myJavaScript.js
isn't being loaded successfully.
Most likely w
is not actually a globally scoped variable like you think it is.
Upvotes: 2
Reputation: 50974
I can't reproduce your problems. You haven't probably define your "w" variable or you defined it away from global scope
http://sandbox.phpcode.eu/g/686fb
try to add at the top of head:
var w = "";
Upvotes: 2