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 (i.e the page elements have been fully rendered)

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


Option #1: Long form syntax

// using jQuery (same as above but with much more intuitive 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

// using jQuery (same as above but with much more intuitive syntax)

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

  // place your code here
})

Option #2a: Short form alternative syntax with ES6

  • Even less typing :)
// using jQuery (same as above but with much more intuitive syntax)

$(() => {
  // 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 & #2a is less typing :)