As you work with JavaScript & jQuery, you will quickly get accustomed to wrapping your JS scripts with a DOM ready check. You generally want to do this, because you don’t want your DOM-manipulating JS to run before the DOM is fully loaded.
The standard jQuery ready function is:
[cc]
$(document).ready(function(){
// Your code here
});
[/cc]
If you’ve seen the jQuery ready shortcut, you can also use this (equivalent to the above):
[cc]
$(function() {
// Your code here
});
[/cc]
How does this work? Diving into jQuery source, you can see on line 173 that jQuery checks if what is passed in is a function and applies [cci]ready[/cci] to it:
[cc]
// HANDLE: $(function)
// Shortcut for document ready
} else if ( jQuery.isFunction( selector ) ) {
return rootjQuery.ready( selector );
}
[/cc]
Also, I want to show how you could wrap your JS code without jQuery. Traditionally, it looks like this:
[cc]
window.onload = function(){
// Your code here
}
[/cc]
Note the traditional way using [cci]window.onload[/cci] will happen later than jQuery’s [cci]ready[/cci] event. Code snippets to run your JS upon DOM ready without jQuery are available online.
Finally, if you want to wait for both the DOM and complete page (including all frames, objects and images) to be loaded using jQuery, you can use:
[cc]
$(window).load(function() {
// Your code here
});
[/cc]
Running JS with jQuery upon DOM ready is simple. Using the jQuery ready shortcut is easy and works well.
jQuery without jQuery is a series that aims to open up the jQuery black box. jQuery is just JavaScript, so you should feel comfortable working at lower levels of abstraction and looking at the jQuery source code written in JavaScript.
diving into jQuery source code for DOM ready http://t.co/tCKfRI3I #jqueryWithoutJquery