jQuery's document ready initialization
Posted February 20th, 2009 in Javascript
jQuery has a $(document).ready() function which is invoked after the DOM is loaded and before the page contents are loaded. It means you don't have to have body onload events and can completely remove all Javascript from your HTML by attaching events to elements independent of the HTML after the DOM has loaded.
I'm always forgetting the correct number of brackets and parentheses to put in when setting up my jQuery files for websites when I first set them up, so this brief post is a quick reference so I can easily locate the code and copy and paste it into my default file.
The basic syntax, which won't actually do anything, looks like this:
$(document).ready(function() {
// initialization code goes here
});
This can be in the <script> section of your HTML file but it is better to put it into an external Javascript file which you would reference like the following example, and which would contain all your Javascript functions:
<script language="javascript" src="/path/to/my.js"> </script>
You are free to put whatever you want to where I've put the comment line "// initialization code goes here", but for readabilty if you have a lot of stuff to initialize then you are probably better to call various other init functions to keep your code nice and clean. For example:
$(document).ready(function(){
init_some_function();
init_some_other_function();
init_another_function();
});
Those other functions might then initialize various other aspects of your code.
Related posts:
- Calling $(document).ready multiple times with jQuery (Friday, September 11th 2009)
- How to tell if an element exists with jQuery (Friday, April 10th 2009)
- Attaching an event to an element with jQuery (Tuesday, February 24th 2009)
- Loading content with jQuery AJAX (Wednesday, January 14th 2009)
- Dynamically get and set an elements content with jQuery (Sunday, January 11th 2009)
- Adding, removing and checking if an element has a CSS class with jQuery (Tuesday, December 16th 2008)

Comments
blog comments powered by Disqus