jQuery $document.Ready Function

By Peter Bromberg

jQuery provides a simple means to trigger the execution of code once the DOM tree, but not external image resources, has loaded.

The formal syntax to define such code (using  a table striping example) is as follows:

$(document).ready(function() {
  $("table tr:nth-child(even)").addClass("even");
});

First, we wrap the document instance with the jQuery() function, and then we apply the ready() method, passing a function to be executed when the document is ready to be manipulated.
We called that the  formal  syntax for a reason; a shorthand form used much more frequently is as follows:
$(function() {
  $("table tr:nth-child(even)").addClass("even");
});

By passing a function to $(), we instruct the browser to wait until the DOM has fully loaded (but only the DOM) before executing the code. Even better, we can use this technique multiple times within the same HTML document, and the browser will execute all of the functions we specify in the order that they are declared within the page. In contrast, the window’s onload technique allows for only a single function. This limitation can also result in hard-to-find bugs if any third-party code we might be using already uses the onload mechanism for its own purpose (not a best-practice approach).

jQuery $document.Ready Function  (2102 Views)