Reputation: 377
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
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:
<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