Document Ready Function

Document Ready Function

  • jQuery (and native Javascript) must wait for a page to be loaded before it can try to dynamically update a page (i.e. Manipulate the page’s DOM)

We can also avoid this issue by adding the <script> tag (the tag we used to link our .js files to our .html files) at the bottom of your html pages right before the closing <\body> tag

  • jQuery provides a “document ready” function that will run once the DOM is fully loaded

  • There are two ways to express the “document ready” function for jQuery


Option #1: Long form syntax

$(document).ready(function(){
  // place your code here
  // jQuery code must be placed inside of a document ready block
})


Option #2: Short form alternative syntax

$(function(){
  // this is the same as the $(document).ready(function(){}) function
  // just much less code

  // place your code here
});

There are no advantages to choosing one syntax over the other. However, option #2 is less typing :)