Hi all. I'm new to Javascript, and I want to ask about the best placement of the script tag.
For example, I have an external Javascript called test.js, which assign event listener with addEventListener function. The question is, where should I put this <script type="text/javascript" src = "test.js" />
?
I saw the example on Yahoo, and they say the best place to put it is in the end of the body tag:
<body>
....
....
<script type="text/javascript" src = "test.js" />
</body>
But on Google Code University video, they give an example, that the best way to put it is in the head, then call one of the function on that script:
<head>
<script type="text/javascript" src = "test.js" />
</head>
<body>
...
init();
</body>
They say the init() function contains code for attaching event listeners to HTML elements, because, if I only put it in the head, the event listeners won't be attached, because the browser haven't parse the HTML elements yet.
But I've recently found an example, that I can still put the script tag in the head tag, without calling the init function in the body tag. Instead, I could write window.onload = init;
on my javascript file.
Can you suggest what's the best way to do this, and why? Or if you have a better technique, could you please explain that to me?