When working with jQuery, it is a good idea to wait for the document to be fully loaded, prior to executing jQuery code on the page. One of the first things you should learn about jQuery is the ready event. Most of your jQuery code will be contained within this handler.
This will ensure that the jQuery code does not run until the DOM is ready. It will confirm that any element being accessed is already loaded and accessible, so the script will not return any errors related to missing elements.
In addition, it also ensures that your code is unobtrusive. The ready event occurs when the DOM (document object model) has been loaded, and the page has been completely rendered (including images).
Because this event occurs after the document is ready, it is generally used to have all jQuery events and functions. The ready() method can only be used on the current document, so no selector is required. The following syntaxes are accepted:
Syntax
$(document).ready(function) $().ready(function) $(function)
HTML Example
We will use the following HTML for the example listed below.
Example
The text within the span element is updated each time the mouse icon is clicked.