jQuery's document ready initialization

Posted 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">

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:


Those other functions might then initialize various other aspects of your code.

Related posts: