What is the difference between these jQuery ready functions?

后端 未结 9 1428
名媛妹妹
名媛妹妹 2020-11-22 15:31

what is difference between

$(function(){

}); 

and

$(document).ready(function() { 

});
相关标签:
9条回答
  • 2020-11-22 15:43

    I suggest you read this. As you can see

    All three of the following syntaxes are equivalent:

    $(document).ready(handler)

    $().ready(handler) (this is not recommended)

    $(handler)

    So it's up to you and to what you prefer.

    0 讨论(0)
  • 2020-11-22 15:49

    $(function(){}) is a short cut for the dom ready

    A function passed as an argument to the jQuery constructor is bound to the document ready event.

    0 讨论(0)
  • 2020-11-22 15:53
    } else if (jQuery.isFunction(selector)) {
        return rootjQuery.ready(selector);
    }
    

    From the source

    Calling $(document).ready(selector) saves a few if statements.

    Although jQuery does cache $(document) internally that might make $(f) faster.

    Benchmarked

    0 讨论(0)
  • 2020-11-22 15:56

    We have run into situations where IE9 does not run functions within $(function() {}); in the same manner or timing as $(document).ready(function(){});

    The issue reared its head for us specifically in reading information out of a query string and processing and displaying that information on the screen, or using it to process a form. IE9 would process the information once it was cached with $(function(), and a user refreshed the page. But on first run, nothing worked right. However, once we switching from $(function(){}); to $(document).ready(), the issue was fixed. We changed NOTHING else.

    I so look forward to the day I don't have to test for IE9 and lower.

    0 讨论(0)
  • 2020-11-22 15:58

    They're effectively the same. No difference.


    This is the native way.

    $(document).ready(function() {
        // code
    });
    

    And this is a shorthand for the previous.

    $(function() {
        // code
    });
    

    jQuery source code

    0 讨论(0)
  • 2020-11-22 15:59

    Both are equivalent, the first is a shorthand form.

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