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 JavaScript Basics (Retired) Introducing JavaScript Review Adding Scripts and Simple JavaScript Commands

What is the best practice of writing javascript either inside end of the body tag or inside end of the head tag ?

where to add javascript for the best pactice

1 Answer

andren
andren
28,558 Points

The best practice these days is to place it at the end of the body tag. Modern browsers pause page rendering while they parse and execute JavaScript.

This means that if you place JavaScript in the head element then your page won't display any content before the browser is done with the JavaScript. Placing it at the end of the body avoids this problem as the page content has already loaded by then.

As an added bonus you'll be guaranteed that all the HTML elements are loaded when your script runs, which they need to be if you want to manipulate them in your code.