For example suppose I have the following within my HTML
<script src="/socket.io/socket.io.js"></script>
The script defines a variable named socket. Immediately below I have the following
<script src="/javascripts/script.js" type="text/javascript"></script>
Within script.js I try to access socket and get a not defined error. However if I use an inline script I can access the variable. How can I access ‘socket’ from within script.js?
JavaScript doesn’t have “includes”, per se.
Any variable declared at the top level of a JS file will be available in global scope immediately after the file is loaded, i.e. at the point the
<script>tag is used.Note that scripts loaded with the
deferattribute on the<script>tag may not be loaded immediately, and so any variables declared therein will not be available immediately.Variables declared with the
varkeyword inside a callback function do not appear in the global scope. So in this code:awill be in the global scope, butbwill not.Whereas in this code:
cwill be in global scope (as it was not declared with thevarkeyword) but not until the callback function has been invoked.