How to execute code when the page loads
A common challenge of JavaScript is executing code only AFTER the referenced elements have been defined. For instance trying to find the contents of a form element will cause errors if that form element has not been rendered to the page yet. Traditional JavaScript uses the window.onload event for this (or a <body onload="initialize();"> type of call). jQuery handles this a little differently.
//assuming an initialize() function has been declared elsewhere on the page
$(document).ready( initialize );
OR
//make use of an anonymous function
$(document).ready( function () {
//initialization code goes here
});
jQuery makes a lot of use of "anonymous" or "inline" functions. In all cases a function reference can be used in their place. (a function reference is the name of a function delcared elsewhere, without the brackets, but this makes passing parameters difficult).
The samples above are roughly equivalent to the traditional onload event with a subtle difference. The onload event only fires after all page elements have completed loading. This may cause delays if you have a large image being referenced. The jQuery ready() method is fired once the DOM tree has been populated. This may happen before all page elements have been loaded. When working with jQuery, the ready() method is the preferred way of initializing a page. However there are no rules that say you cannot use an onLoad event in conjunction with jQuery.
An added bonus of the jQuery way is that you can have multiple ready() definitions. This is the case with all jQuery events. For instance:
$(document).ready(function () { alert("Number One"); });
$(document).ready(function () { alert("Number Two"); });
In this sample BOTH alerts will be fired as soon as the DOM tree is ready. These two ready() definitions could have been anywhere in our code, separtated by many lines of other code. More on this concept when we talk about jQuery events.
- Printer-friendly version
- Login or register to post comments

TMW2jDRc
drug testing
home test kits
detox drinks
drugtests
lemon detox