jQuery Document Ready Function

It is not safe to begin manipulating an HTML document until it has fully loaded. To only run a function once everything on a page has loaded, we can use the jQuery ready() method and pass a function as the first argument.

 

To demonstrate this, let's create a simple function that will run once the Document Object Model (DOM) is in a ready state.

 

$(document).ready(function () {
  console.log('The document is ready.');
});
The document is ready.

 

Calling Multiple Functions with jQuery ready()

To call multiple functions with a single jQuery ready() method, create named functions and pass them as a comma-separated list inside ready().

 

function firstReady() {
  console.log('First ready function.');
}

function SecondReady() {
  console.log('Second ready function');
}

$(document).ready(firstReady(), SecondReady());
First ready function.
Second ready function.

 

jQuery ready() Shorthand Version

It is possible to replace the more verbose $(document).ready() with $() to achieve the same functionality.

 

function onReady() {
  console.log('The document is ready.');
}

$(onReady());
The document is ready.

 

The downside to the shorthand version is it is less obvious that jQuery is running the function when the DOM is ready.

jquery dom