jQuery document ready function

This is one of the most useful elements of jQuery!

The jQuery $(document).ready() method completely negates the need to place scripts in the HTML page to avoid errors caused by elements of the page being required by the script but not being loaded.

This function effectively pauses the whole script until the page and all its assete have loaded. As a result, all HTML elements and all attached elements (stylesheets, images etc) will be available to the script when called regardless of where the script is placed. This allows the jQuery and JavaScript code to be removed from the <body> of the HTML page and placed in an external file with a .js extension. This carries with it all the advantages of using external CSS files.

The $(document).ready() method requires a blind function (a function defined inline with the method and without a name) be used to house the script to be run. Without this function the code would execute as normal as the page loads.

The syntax looks like this:

$(document).ready(function() {
   // jQuery or JavaScript code here
});

Further reading

Read the jQuery $(document).ready() method tutorial.

Exercise!

Now open the jQuery document ready exercise page and work through it.

You will need to use the jQuery documentation, specifically the html() method.

You may also use the JavaScript scratch pad to try out code quickly.