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?

Steve Souders excellent book "High Performance Web Sites" recommends the end of the body. Prior to reading Souders, everyone used the <head> section.

If you have a single

document.getElementById()

in the code, you don't know if you will get your element or a null, unless your JavaScript is the last thing to load.

If you like irony, Sounders has moved from Yahoo to Google.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.