Richard Korts
asked on
Location of Javascript on HTML page
I have been doing websites for over 20 years. Traditionally, I always thought that the Javascript had to be in the document <head> section.
I gather now it can be anywhere, paired by <script>......</script>
Is that true?
I gather now it can be anywhere, paired by <script>......</script>
Is that true?
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Addendum to Rob and Terry's post.
There can be an order requirement in how you place scripts.
For example
If you are emitting jQuery or JavaScript with a library dependency and you put your scripts before </body> you could run into this problem. The solution is to place in the head or to cache your script output and emit it all at the end.
Having said that random script output in my view is bad design so a well designed page should not run into these problems.
If you are really interested in performance you would pack your JS and CSS files into single files for final deployment of your site so there is only one file which you could then include.
There can be an order requirement in how you place scripts.
For example
<script>
$(function() {
$('.someclass').click();
});
</script>
<script src="http://code.jquery.com/jquery.js"></script>
Will generate an error because $(function) uses jQuery which the browser does not know about yet.If you are emitting jQuery or JavaScript with a library dependency and you put your scripts before </body> you could run into this problem. The solution is to place in the head or to cache your script output and emit it all at the end.
Having said that random script output in my view is bad design so a well designed page should not run into these problems.
If you are really interested in performance you would pack your JS and CSS files into single files for final deployment of your site so there is only one file which you could then include.
It's become accepted practice to put scripts at the bottom of the page, just before the body end tag. That way the browser does not "see" that script until your page (the DOM) is loaded