Where to place your Javascript code


I’m currently trying to learn Javascript and so far I like it, but questions are arriving as I’m learning and here is one, so far most of the examples I have seen in books, tutorial etc. placed the Javascript code either directly in the body section or the header and I was wondering which of these two is the best practice, or even better is it possible to have my Javascript externally as with CSS or some other languages like Actionscript where the code can reside in a classes or external files?

Can someone give me some advice as to what is the best practice when placing your JS code?


Yes you can place your JavaScript in an external file and link to it from the .HTML.

whatever.js could be the name of a file and to link it:

<script type="text/javascript" src="whatever.js"></script>

Where this goes can depend on what your scripts are doing. If they’re effecting the page as it loads in the browser, then it may be dependent on the HTML elements already existing. So you would place it at the bottom of the page right above the closing body tag </body>

Thanks a lot for your reply!