Four variations of jQuery ready() — what's the difference?

后端 未结 4 549
鱼传尺愫
鱼传尺愫 2020-12-09 12:41

I\'ve seen four different ways to tell jQuery to execute a function when the document is ready. Are these all equivalent?

$(document).ready(function () {
           


        
相关标签:
4条回答
  • 2020-12-09 13:15

    Also it should be mentioned, that symbol that you pass to function will be use inside the function. For example:

    $(function(jQuery) {
       // now I can use jQuery instead $
       jQuery("body").append("<div></div>"); // adds div to the end of body element
    }); 
    

    if you want use $ - you can leave function's param in this situation empty

    The real example you can find here http://jsfiddle.net/yura_syedin/BNgd4/

    0 讨论(0)
  • 2020-12-09 13:15

    Here's another one - starts like this...

    (function (jQuery) {
    

    then to finish...

    })(jQuery);
    

    An example is here: http://jsfiddle.net/C2qZw/23/

    0 讨论(0)
  • 2020-12-09 13:18

    There is no difference.

    $ is the same as jQuery. If you view the unminified source, you will see var $ = jQuery = ... or something to that effect.

    The jQuery function checks the type of it's parameter, if it is a function, it treats it the same as $(document).ready(...)

    Calling jQuery without a parameter defaults to using document. So $() and $(document) are identical. Try it in Firebug.

    0 讨论(0)
  • 2020-12-09 13:23

    re: Geroge IV's comments regarding $() == $(document) its correct. From the unminified source (init is what get called internally):

    init: function( selector, context ) {
        // Make sure that a selection was provided
        selector = selector || document;
    

    Also from source, to back up previous conversations:

    // HANDLE: $(function)
        // Shortcut for document ready
        } else if ( jQuery.isFunction( selector ) )
            return jQuery( document ).ready( selector );
    

    this should be community wiki. I've always been interested in the inner workings of jquery, now I've had an excuse to start looking :-)

    0 讨论(0)
提交回复
热议问题