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.
Why is this script element not at the end of the body tag?
I noticed that the code Dave is writing has the script element outside the body. Does anybody know the reason for that? We have learned that best practice for placing the JS code is at the end of the body tag. And I have even experienced issues if with my code when I didn't follow this advice. This is why I was wondering about his positioning.
Steven Parker220,426 Points
Scripts that only load libraries, define functions, or establish data resources can be safely loaded in the "head" section of the page, and it is a common practice to do so.
But any script that interacts with the DOM should always be loaded as the last thing in the "body" section, and as you have seen can create errors if it is loaded before the page elements that it references.
This script is an example of the first kind since it defines functions that don't run until the page button is clicked.
Thank you Steven! I got confused for a second there. Sometimes I feel that I don't have full knowledge of where it's best to place some lines of code. But your explanation makes a lot of sense.