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

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).