jQuery $(document).ready() is a basic part of using jQuery. Document ready event is a self-executing function which fires after the page elements have loaded. jQuery document ready is used to initialize jQuery/JavaScript code after the DOM is ready, and is used most times when working with jQuery.
There are different ways of writing Document Ready functions typically used in jQuery:-
Example 1:
$(document).ready(function() {
// Put javascript here
});
Example 2:
$(function(){
// put jQuery code here
});
The above two codes are literally similar.
Example 3:
jQuery(document).ready(function($) {
// put jQuery code here
});
Adding the jQuery can help prevent conflicts with other JS frameworks.
Conflicts arises because many JavaScript Libraries/Frameworks use the same shortcut name which is the dollar symbol $,hence the browser gets confused.To prevent conflicts jQuery namespace is recommended,then you call $.noConflict() to avoid namespace difficulties.
jQuery.noConflict(); // Reverts '$' variable back to other JavaScript libraries, avoiding namespace difficulties
jQuery(document).ready( function(){
// Put javascript here when DOM is ready with no conflicts
});
Example 4:
(function($) {
// code using $ as alias to jQuery
$(function() {
// more code using $ as alias to jQuery
});
})(jQuery);
// other code using $ as an alias to the other library
This way you can embed a function inside a function that both use the $ as a jQuery alias.
Example 5:
$(window).load(function(){
//initialize after images are loaded
});
if you want to execute code when the HTML doc is completely loaded,i.e,the DOM and its content,then this method is used.
0 Comment(s)