These are the different types of Document Ready functions typically used in jQuery (aka jQuery DOM Ready). A lot of developers seem to use them without really knowing why. So I will try to explain why you might choose one version over another. Think of the document ready function as a self-executing function which fires after the page elements have loaded.
Document Ready Example 1
1
2
3
|
$(document).ready( function () {
});
|
Document Ready Example 2
This is equivalent to example 1… they literally mean the same thing.
Document Ready Example 3
1
2
3
|
jQuery(document).ready( function ($) {
});
|
Adding the jQuery can help prevent conflicts with other JS frameworks.
Why do conflicts happen?
Conflicts typically happen because many JavaScript Libraries/Frameworks use the same shortcut
name which is the dollar symbol $. Then if they have the same named functions the browser gets
confused!
How do we prevent conflicts?
Well, to prevent conflicts i recommend aliasing the jQuery namespace (ie by using example 3 above).
Then when you call $.noConflict() to avoid namespace difficulties (as the $ shortcut is no longer available)
we are forcing it to wrtie jQuery each time it is required.
1
2
3
4
5
6
7
8
9
10
|
jQuery.noConflict();
jQuery(document).ready( function (){
});
jQuery.noConflict();
( function ($) {
})(jQuery);
|
Document Ready Example 4
1
2
3
4
5
6
7
|
( function ($) {
$( function () {
});
})(jQuery);
|
This way you can embed a function inside a function that both use the $ as a jQuery alias.
Document Ready Example 5
1
2
3
|
$(window).load( function (){
});
|
Sometimes you want to manipulate pictures and with $(document).ready() you won’t be able to do that
if the visitor doesn’t have the image already loaded. In which case you need to initialize the
jQuery alignment function when the image finishes loading.