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 trial

JavaScript

Josh Rubner
PLUS
Josh Rubner
Courses Plus Student 6,766 Points

Script tags go before the closing body tag or in the head?

In this video, Dave uses the head to hold script tags.

I've been told to put script tags at the bottom of the body, so the page loads the structure and styling before the JS can fail.

Is there a definitive answer?

3 Answers

Patrick Vanegas
Patrick Vanegas
6,971 Points

Typically, you add scripts to the bottom of your HTML, that way the page loads first so that the user can see the full website at first glance. This is why some websites display the header first, and then everything else pops up later, for example. Some pages take time loading up the scripts. You could place them anywhere, but it's just good practice to place them in the bottom so that it can load more efficiently. Hope this helps!

Adding to what Patrick said...

The idea is to make sure the DOM is ready before you start using it. HTML is parsed from top to bottom. So putting the script tag at the very bottom before the closing body tag makes perfect sense. Putting the script tag in the head is okay, but you have to make sure that it runs only after the DOM has completely loaded -- you use something like the DOMContentLoaded event or jQuery's ready() method.

Patrick Vanegas
Patrick Vanegas
6,971 Points

Your welcome, Josh! Just remember to always place them right before the closing body tag and you're set!