Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

JavaScript AJAX Basics (retiring) Programming AJAX Parsing JSON Data

Why isn't Dave putting his <script> tags at the end of the body?

We have been taught to put <scipt> tags at the end of our body tags, am i missing something?

Thanks :)

2 Answers

Jason Anders
Jason Anders
Treehouse Moderator 145,623 Points

Hi there,

While it is often Best Practice to include the JS script files at the end of the HTML, there are many times where this might actually break the site instead.

Placing the JS at the end allows the page to fully load before the JavaScript is loaded. This will often speed up the page load, as it isn't waiting for the JavaScript to load before finishing the HTML rendering.
However, if elements on the page are reliant explicitly on JavaScript, as it is here, the JavaScript will need to load completely before the page loads, or the page will not function properly. Here, you're using JavaScript to retrieve data from the server to render on the page, but if the JavaScript is run after the page loads, then the page doesn't have any the data it needs to render, so your data will not show on the page.

So, while it is often true that the best place is at the end, there are many times where placing the JavaScript <script> tags in the header is better and necessary.

I hope that helps clear it up.

:) :dizzy:

James Churchill
James Churchill
Treehouse Teacher

Thanks for the great answer Jason!

James Churchill
James Churchill
Treehouse Teacher

Hi there!

Knowing where to put <script> tags can be a bit tricky. One of the advantages of putting <script> tags just before the closing <body> tag, is that you know you can safely access other elements on the page, without having to write any extra code.

Unfortunately, there are downsides to this approach. For a detailed overview of the various options that exist (including the new async and defer <script> tag attributes), check out this community post:


Thanks ~James