Jquery Handler
Course- Javascript >
At various places through this book you used the window.onload handler. jQuery has its own equivalent:
$(document).ready(function() { // jQuery code goes here });
Pretty much all the jQuery code you write will be executed from within a statement like this.
Like window.onload, it accomplishes two things:
- It ensures that the code does not run until the DOM is available—that is, that any elements your code may be trying to access already exist—so your code doesn’t return any errors.
- It helps make your code unobtrusive, by separating it from the semantic (HTML) and presentation (CSS) layers.
The jQuery version, though, has an advantage over the window.onload event; it doesn’t block code execution until the entire page has finished loading, as would be the case with window.onload. With jQuery’s (document).ready, the code begins to execute as soon as the DOM tree has been constructed, before all images and other resources have finished loading, speeding up performance a little.