# when we need to add some javascript code to html, where we have to put it?

when we need to add some javascript code to html, where we have to put it?

What is the best practice:

in line:

<script type="text/javascript">document.write(new Date().getFullYear())</script>


or centralized:

<header><script type=text/javascript> document.getelementbyid('someid').innerhtml='date'.....</script></header>


Optimally, it's loaded just before the body tag closes

    <!-- all html above here -->
<script src="..."></script>
</body>


for the following common reasons:

• The DOM elements that you are operating are safely parsed by then.

• Script tags block execution. If they delay in loading and/or parsing, the things that follow it will have to wait. Thus, to prevent delay and from seeing a blank screen while scripts load, we load the page first, scripts last.

I have a similar answer, along with other answers, at StackOverflow which should explain more.

• Thanks for your answer, but it mean that all scripts in header shuold be placed in the bottom of the page? or only the scripts that interacts with elements in the page like my above example? Common functions should be placed in header? eg function setCookie(cname, value) { document.cookie = cname + "=" + value; //+"; path=/; expires=Wed, 1 Jan 2020 00:00:00 GMT"; } – user2119955 May 10 '13 at 10:47
• @user2119955 Usually they are placed at the bottom since loading and parsing could potentially block the page. For embedded scripts (scripts in the HTML itself), they are excused from the loading time, but still, parsing could still take time. Besides, it's recommended to use external JS rather than embedded JS. – Joseph May 10 '13 at 11:04