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

Meredith Klein
Meredith Klein
10,870 Points

Why do we always use the $(document).ready function in the <head> instead of putting the whole script before </body>?

Is there a specific reason or is it a matter of preference?

3 Answers

As I understand it they are both similar and are a matter of preference. Since the html document loads top down, like most other software languages, it will load the JavaScript files as soon as it encounters them, unless they are wrapped in the "$(document).ready" function, in which case it will wait until the rest of the page loads. However, if you put your script tags at the bottom of the body right before the closing body tag, the JavaScript file(s) will also load last. Personally, I find this to be more elegant as it reflects normal code organization instead of having some random code that conditionally waits to load and acts as an exception to the standard top-down code flow.

From what I've seen, it can be done, and work, either way. However, it is more correct to put your script or a link to your script before the closing body tag. That lets the document load before loading the script, essentially doing the same thing as using $(document).ready.

Meredith Klein
Meredith Klein
10,870 Points

thank you both for answering!