Reputation: 5089
I've been developing in javascript for a few months and I have been using $(document).ready(function(){
at the beginning of all my scripts. I've noticed other folks don't use this in their scripts but I can't seem to get mine working without it. I'd like to keep my code cleaner, but for all my google searches I can't seem to figure out how to get rid of it.
I know it tells the browser to execute my script as soon as the page loads but is there something global I can set so that I don't need to explicitly tell the browser to execute each of my scripts when the page loads? Or is it a more global problem with where in my html files the scripts are located?
Upvotes: 3
Views: 928
Reputation: 20415
All $(document).ready(function() { ... });
or $(function() { ... });
does is wait for the document to be ready for manipulation. You should use $(document).ready(function() { ... });
or $(function() { ... });
if your scripts are inline or in the <head />
section because JavaScript executes in the order in which it appears on the page otherwise.
To do away with $(document).ready(function() { ... });
or $(function() { ... });
, simply move your scripts down to the bottom of the page after all of your content, right before the closing </body>
tag.
Putting the scripts at the bottom is really a best practice anyway. For this and other best practices, I recommend you take a look at Html5Boilerplate and Yahoo! Best Practices.
Upvotes: 6
Reputation: 42350
the $(document).ready()
convention is part of jQuery, not just JavaScript. From their' documentation on the ready function:
This is the first thing to learn about jQuery: If you want an event to work on your page, you should call it inside the $(document).ready() function. Everything inside it will load as soon as the DOM is loaded and before the page contents are loaded.
So yes, it is required. jQuery does come with a shorthand for this though, so you could do the following:
$(function() {
//jquery code
};
Upvotes: 1
Reputation: 7011
You're needing document.ready probably because you're interacting with the DOM before it loads. How can the script manipulate elements that are not there yet?
If you stick your script at the end of the file you will not need it. It's also good practice to do so for a lot of Javascript files as they can take time to process (especially if they're hosted externally). Putting them at the end of the file often speeds up the page load time.
Upvotes: 7