1

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?

3
  • You're trying to access the variable when the socket-script hasn't loaded yet. Use $(document).ready() or something. Commented Mar 12, 2012 at 11:58
  • What is the code for socket.io.js? Commented Mar 12, 2012 at 12:02
  • If this is socket.io, it exports a variable called io, but not one called socket. Commented Mar 12, 2012 at 13:42

2 Answers 2

2

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 defer attribute on the <script> tag may not be loaded immediately, and so any variables declared therein will not be available immediately.

Variables declared with the var keyword inside a callback function do not appear in the global scope. So in this code:

var a = 1;
$(document).ready(function() {
    var b = 1;
});

a will be in the global scope, but b will not.

Whereas in this code:

$(document).ready(function() {
    c = 1;
});

c will be in global scope (as it was not declared with the var keyword) but not until the callback function has been invoked.

Sign up to request clarification or add additional context in comments.

Comments

0

Where are you defining these scripts? Are they on the head tag? If so, you should be able to access variables between scripts...

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.