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 trialMark Glissmann
7,225 Points<script> Position in HTML doc
Is there a particular reason why the <script> element is placed at the bottom of the HTML doc right before the closing </body>? Would the script work the same if it were placed in the <head>?
1 Answer
Nejc Vukovic
Full Stack JavaScript Techdegree Graduate 51,574 PointsHi Mark,
The reason is that that way you make sure that the HTML DOM is fully loaded before your script runs. Then you don't need to use $(document).ready in jQuery for example.
Mark Glissmann
7,225 PointsThank you Nejc!
Yaroslav Kleshchev
8,744 PointsYaroslav Kleshchev
8,744 PointsThis is to insure that the page is fully loaded before the script runes. Otherwise you might run in to some problems if the script runes before every thing is loaded. In JavaScript that are a few things you can do to avid doing this. One way is to rune check if the page is fully loaded;. Like this: if (document.readyState === "complete") { do something }. You can also use the jquery.ready to check if your page is loaded. And of course you can just put the script tag at the bottom of the page for an easy fix.