简体   繁体   中英

Self calling functions inside of $(document).ready(function(){ … });

I've already encapsulated my javascript in

jQuery(document).ready(function($) {

});

I was wondering what the implications were of calling functions inside of it via these two ways:

jQuery(document).ready(function($) {
    $(function () {
        // do something
    });
});

vs

jQuery(document).ready(function($) {
    (function () {
        // do something
    })();
});

edit:

I also wanted to know which of the two would be the more "correct" manner of doing things? Feel free to add your own implementation.

In difference lies in the order of execution:

jQuery(document).ready(function($) {
    $(function () {
        // inner handler
    });
    // outer handler
});

Code inside the inner ready handler is executed after the code in the outer handler: http://jsfiddle.net/nmD8b/ .

jQuery(document).ready(function($) {
    (function () {
        // do something
    })();
    // outer handler
});

Code inside the immediate function expression is executed right where the function is defined, ie before code following the expression: http://jsfiddle.net/nmD8b/ .


If you want to scope variables, use the second way. The first way does not make a lot of sense, you should only register ready event handlers when you actually need them. In this case, the DOM is already ready, because you bind the handler inside another ready handler.

If you don't want to scope variables, use neither of them. Just put all your code inside the outer handler.

jQuery(document).ready(function($) {

&&

$(function () {

Are the same thing

Except the 2nd one only works in jQuery 1.0+ (i think, someone correct if wrong)

Furthermore

the $ is a shorthand symbol for the jQuery namespace. Thus jQuery( is the same as $( . You could then write $(document) which would be the same as jQuery(document) , where the $ is the namespace shorthand, the () feed the parameter given which, in this case, is document which is the same in javascript.

$(function is jQuery's doc.ready call function, and the normal return would be what is commonly referred to as a jQuery Object . Where index 0 is the element passed through, and everything else is either native js returns on that element or jquery props and methods.

As everyone is stating:

jQuery(document).ready(function ($) { });

// is the document.ready as:

jQuery(function ($) { }); // <-- this is the short-hand version

// the $ inside the parenthesis really just means that $ is to refer to jQuery inside.
// you could just do:

$(function () { }); // if you know it will be anyway 

Using immediate functions is more so for creating "classes" / "namespaces" etc in regular Javascript.

(function (myNamespace) {

    function myNamespace () { }
    return myNamespace;

}(window.myNamespace = window.myNamespace || {}));
  • Using $(function () {}); anytime after the document is ready is perfectly safe, the specified function will fire immediately. Quote :

If .ready() is called after the DOM has been initialized, the new handler passed in will be executed immediately.

Note: as pointed out be Felix, jQuery appears to prevent nested invocation of .ready() .

  • Using (function () {})() works as expected whether used inside or outside document ready event. It (i) creates a closure (ii) fires immediately (iii) does not care if document is ready.

The first one is redundant so IMO the second one is better.

In fact, if you do not need a closure then make the function inline; $(function () {}); acts as a closure on its own.

Given that $(function() {}) is an alias for $.ready , your first example is simply a $.ready wrapped inside a $.ready , which doesn't really make any sense, even if I don't think that it has any severe performance implications.

Your second example is what people usually do on the outermost part of their JavaScript files to prevent pollution of the global variable scope :

;(function($) {
    $(document).ready(function() {
        // Do something
    });
})(jQuery);

That is what I've seen in most JavaScript files so far. It prevents global variable scope pollution and makes sure that $ actually refers to jQuery even in noConflict mode.


An important thing to note about $.ready is that you don't really need it if you load your JavaScript just before the closing </body> tag (doing that also improves page load time ).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM