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 144,350 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