Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Writing jQuery document.ready in multiple ways

    • 0
    • 2
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 654
    Comment on it

    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)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: