BaleineBleue
BaleineBleue

Reputation: 377

Put Socket.IO in the html head tag

So I have been doing socket.IO and I started with the chat example. My chat service is quite elaborate now, but it is based off of the original tutorial. In the tutorial they put

<script src="/socket.io/socket.io.js"></script>
<script src="/script.js"></script> 

at the end of the body tag. For organizational reasons, I would like to put the script tags in the head, but when I do so, my code no longer works. I am curious as to why this happens, even if there is not a possible solution.

Upvotes: 0

Views: 357

Answers (1)

zoecarver
zoecarver

Reputation: 6403

You can place <script> tags anywhere in your HTML (within reason). The only problem that you may run into with putting your <script> tags in the <head> is that they will load first. The way HTML works is that it goes through the code in order, this means that if you try to reference something in your code HTML code from your JavaScript and your JavaScript comes first, you will get an error that it cannot find the element you are referencing.

To avoid this, JS is often put last. If for some reason you need the JS in the <head>, you have two options:

  • Put your code inside of a button. This works because the document will load everything and then only run the JavaScript that references the HTML when the button has been pressed.
  • If you don't want the user to have to press the button, or a button does not work for some other reason, you can use built in functions like <body onload="script();">. This example will run the code inside of script() only after the body has loaded. If this does not work, you can use other similar funcions like document.onload = function ... or jQuery's $( document ).ready()

Hope this helps!

Upvotes: 1

Related Questions