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 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
231,236 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!