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

which version of document.ready is this?

I know there's different ways to do it..that is, make sure the html is loaded before the JS runs. This is the most recent one I've seen.

var main = function(){
  //code goes in here
}
// this goes at the bottom of the page
$(document).ready(main);

Just wondering if it's new, old or something in the middle

$(function(){
  // prior to treehouse
  //I had seen it mostly like this
  //all code in here runs after the document loads
});

$(document).ready(function(){
  //w3schools has it as this
});

//Andrew has us putting the link at the bottom of the index 
//with the link to the js file
//so that the index loads before the js

```html
//from the jQuery basics course index file


<script src="http://code.jquery.com/jquery-1.11.0.min.js" type="text/javascript" charset="utf-8"></script>
    <script src="js/app.js" type="text/javascript" charset="utf-8"></script>

I'm sure there's other ways also. Just seems like everyone has a different way of doing stuff, which is fascinating...

3 Answers

Steven Parker
Steven Parker
229,608 Points

:point_right: That's the standard JQuery ready function

I'm not sure what you mean by "version". I think all versions of JQuery have this. Perhaps you are thinking of methods for waiting that don't require JQuery, like the onload event.

:information_source: Your last line can be abbreviated as just this (it does the same thing):

$(main);

Thanks, I like succinct.

Dan Weru
Dan Weru
47,649 Points

Hello Larson,

It's the same function you're used to. The implementation is just a little different; instead of wrapping the function in the $(document).ready() function like this,

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

they instantiate (save) the function in a variable, then pass the variable to it instead. When you think about it, the end result is the same.

Note that the function won't be called up until the

 $(document).ready(main);

line is reached.

Thanks Daniel, I didn't know the ins and outs of how it worked. I appreciate the explanation.

Dan Weru
Dan Weru
47,649 Points

You're most welcome, anytime.