Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialbaderbouta
7,804 PointsWhy 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
Treehouse Moderator 145,860 PointsHi 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.
:)
James Churchill
Treehouse TeacherHi 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:
https://teamtreehouse.com/community/best-practice-where-to-include-your-script-tags
Thanks ~James
James Churchill
Treehouse TeacherJames Churchill
Treehouse TeacherThanks for the great answer Jason!