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.

Development Tools Introduction to Front End Performance Optimization Combine and Minify Assets Optimize JavaScript

Can I use $(document).ready(function(){} instead of loading JS scripts at the bottom of the HTML? Are they different?

I have my scripts at the top of my HTML. In my JS files I wrap my code in $(document).ready(function(){ "All my other JS" }. I thought this basically did the same thing, waiting to load the JS until the page was finished loading. Should I change this or can I keep it the same? (For the purposes of optimization).

Thank you for your response!

2 Answers

LaVaughn Haynes
LaVaughn Haynes
12,397 Points

Yes. If you want to put your script at the top of your page then you can use $(document).ready() to keep your javaScript from running until the page has loaded.

For example, if your javaScript at the top of the page tries to select all of the paragraphs and change the font color before the paragraphs have actually loaded then it won't work.

Alternatively you can just move your script tags to the bottom of the page. By the time your browser gets to the javaScript, all of the HTML will be loaded so you won't need to use $(document).ready(). Another benefit of including the script at the bottom, as Ryan was saying, is that your page will appear to load a little faster since all of the HTML that displays the page will be loaded before the browser even bothers to try to load the javaScript.

Thank you for your response!

Ryan Chatterton
Ryan Chatterton
5,914 Points

Unless you need the Js code it is running to be blocking (loading js first before html). .ready is waiting until the doc is in a "readiness state", and placing at the bottom causes the html code to get loaded first before the browser does any work with reading the js code. (ie. not blocking the page loading while your browser reads your js before it starts to render the html).