Taken together, $()
and .addClass()
are enough for us to accomplish our goal of changing the appearance of the poem text. However, if this line of code is inserted alone in the document header, it will have no effect. JavaScript code is generally run as soon as it is encountered in the browser, and at the time the header is being processed, no HTML is yet present to style. We need to delay the execution of the code until after the DOM is available for our use.
With the $(document).ready()
construct, jQuery allows us to schedule function calls for firing once the DOM is loaded—without necessarily waiting for images to fully render. While this event scheduling is possible without the aid of jQuery, $(document).ready()
provides an especially elegant cross-browser solution that includes the following features:
It uses the browser's native DOM-ready implementations when available and adds a window.onload
event handler as a safety net
It allows for multiple calls to $(document).ready()
and executes them in the order in which they are called
It executes functions passed to $(document).ready()
even if it is called after the browser event has already occurred
It handles the event scheduling asynchronously to allow scripts to delay if necessary
It simulates a DOM-ready event in some older browsers by repeatedly checking for the existence of a DOM method that typically becomes available at the same time that the DOM as a whole is ready
The .ready()
method's parameter can accept a reference to an already defined function, as shown in the following code snippet:
Listing 1.1
However, as demonstrated in the original version of the script and repeated in Listing 1.2, the method can also accept an anonymous function:
Listing 1.2
This anonymous function idiom is convenient in jQuery code for methods that take a function as an argument when that function isn't reusable. Moreover, the closure it creates can be an advanced and powerful tool. It may also have unintended consequences and ramifications on memory use, however, if not dealt with carefully. The topic of closures is discussed fully in Appendix A, JavaScript Closures.