Pregunta

In my html file, I'm doing this:

<script src="http://[node server]:3000/socket.io/socket.io.js"></script> 
<script type="text/javascript" src="file.js"></script>

And in my file.js, I can now usesocket.io features.

How is the socket.io stuff made visible to file.js?

¿Fue útil?

Solución 2

Any script included in this way doesn't run in it's own context. Instead all scripts are executed within the context of the window that loaded them, meaning any objects or methods loaded in one script will be available in other scripts executed within the same window.

The order matters here, too. If file.js was included first, any references to objects or functions defined in socket.io would be undefined. That is, unless you have some sort of delayed execution mechanism in file.js which waits until the rest of the document is loaded to execute.

And, of course, this also applies to inline scripts. For example:

<!-- defines myFunc -->
<script type="text/javascript" src="my.js"></script> 
<script type="text/javascript">
    myFunc(); // call myFunc
</script> 

Otros consejos

If you've come from a include strict language it's a little odd in thought. Javascript is in global scope, so as long as you include a javascript file before referencing it in a 'lower' file you'll have access to everything from the first javascript.

Think of it as pasting it all into one big single file, I guess.... :)

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top