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.

JavaScript AJAX Basics (retiring) jQuery and AJAX The Office Status Project Revisited

Justin Sze Wei Teo
Justin Sze Wei Teo
9,418 Points

$(document).ready function

Hi guys,

In the video, Dave uses the following code to start off in widget.js

$(document).ready(function() { });

He says the reason he writes this jQuery function in is because he wants the HTML to load first before any javascript in widget.js is executed, since the script tag is located in the head of the HTML document.

My question is, if he wanted all the HTML to load first before javascript is run, why doesn't he simply place the script tag at the bottom of the HTML tag, as opposed to its head?

Kindly advise, thanks guys!

2 Answers

Steven Parker
Steven Parker
217,577 Points

It could be a preference for keeping the references to external resources together.

Functionally, loading the scripts at the end would work, but it's nice to have all your external references together.

:information_source: The "$(document).ready(handler)" syntax is deprecated. The recommended replacement is the more compact equivalent: "$(handler)".

Justin Sze Wei Teo
Justin Sze Wei Teo
9,418 Points

Thanks for this, appreciate your swift answer

Patryk Bernasiewicz
PLUS
Patryk Bernasiewicz
Courses Plus Student 10,281 Points

In JavaScript, it's considered a good practice to keep your scripts encapsulated inside functions. When using jQuery, programmers usually encapsulate their code in $(document).ready(function() { }) block for convenience - not only it lets you keep your code encapsulated, thus not letting anything in the outside access its variables, but also assures you that the code will run only when the website is loaded - when the document is ready.

Justin Sze Wei Teo
Justin Sze Wei Teo
9,418 Points

Thanks for this! Appreciate the added info!