Why use the document ready script

There are several stumbling blocks for jQuery-beginners.

One of those is to overlook the importance of the document ready script.

If you put your scripts in the head section always start your script this way:

This short tutorial is intended to help you understand what these few lines of jQuery code do and realize their importance for any script.

The code starts with the jQuery alias  which turns the document (= the HTML page) into a jQuery object. It then attaches the ready method which checks if the document is ready before invoking any other jQuery script.

Why is this so important?

Most of what jQuery does is FIND SOMETHING and DO SOMETHING. Scripts are used to iterate over elements (headings, paragraphs, images, etc.) on a web page and then do something to those elements. If the elements on a page aren’t available then the effect of a script would be nil.

The browser first needs to load all the elements on a web page and create the so-called DOM. The Document Object Model is the tree with the hierarchical relationship between the elements on a web page (see image).

Document Object Model

When the DOM has been created we say that the document is ready. If we write a script that has to find all the h2 elements it can work its way through the DOM to find them and then do something to them.

With the document ready script we make sure that the content of the web page is loaded, but we don’t wait for the images to have been loaded. If you want to do something to one or more images with your script you need another ready script. Which I will tell you about in another tutorial.

If you insert your script(s) just before the closing body tag you do not need to use the document ready function. Because all of the markup is loaded before the script the DOM has already been created and the script can act upon it.

Add your comment