Learn about the jQuery document ready function.
Before you start tinkering with elements on a web page you need to wait until the DOM has been loaded. That’s where the jQuery document ready function comes in.
In order to only execute our jQuery code when the DOM has been constructed we can use the document ready method provided directly from the jQuery library.
To explain, we’re basically using jQuery to select the document element (basically the entire DOM) and pass in an anonymous function to the ready method that contains the code that should be run once the page is fully loaded. Simple enough?
You’ll be pleased to know that there is also a shortcut to doing this.
So you can omit the document element and also the ready function and just pass in the anonymous function to the jQuery function. That should save a couple of bytes of bandwidth within your code!
Using the document ready function ensures you are only working with elements that are actually there on your page. Therefore it’s a good idea and good practice to write all of your jQuery code inside the document ready function.