You should put JavaScript right before </body>
. Ideally, your HTML should function without JavaScript, so it should be one of the last things loaded.
Bear in mind that you should use CSS to hide elements and not JavaScript. This avoids seeing elements appear and disappear as the page loads.
You may also come across the following problem...
Problem
In this scenario, I'm going to use PHP as an example.
Your footer.php
file may currently look like this:
<script src="jquery.js"></script>
<script src="custom.js"></script>
</body>
</html>
But what happens on the rare occasions you want to add some <script>
exclusively for one page? You wouldn't be able to put it after footer.php
because you wouldn't be in the <body>
tag anymore, but you can't put it before, because then you'll be missing the jquery.js
from your code.
Solution
Have a footer-start.php
file:
<script src="jquery.js"></script>
<script src="custom.js"></script>
And a footer-end.php
file:
</body>
</html>
And have your footer.php
be simply:
<?php
require 'footer-start.php';
require 'footer-end.php';
Then, on the rare occasions that you need to use a custom <script>
for one page, do this:
<?php require 'footer-start.php'; ?>
<script>...</script>
<?php require 'footer-end.php'; ?>
Doing it this way means you don't have to change all your previous code where footer.php
is referenced.