2

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.

Mark Pieszak - Trilon.io
  • 61,391
  • 14
  • 82
  • 96
lorenzoid
  • 1,812
  • 10
  • 33
  • 51
  • 1
    The first example adds another function to the `ready` queue of functions (if I remember correctly). The second way just creates a self-executing anonymous function. I suggest using the second way, as they both do pretty much the same thing. – Blender Nov 01 '12 at 18:25

5 Answers5

4

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, i.e. 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.

Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
1
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.

SpYk3HH
  • 22,272
  • 11
  • 70
  • 81
1

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 || {}));
Mark Pieszak - Trilon.io
  • 61,391
  • 14
  • 82
  • 96
1
  • 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.

Salman A
  • 262,204
  • 82
  • 430
  • 521
0

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).

Community
  • 1
  • 1
fresskoma
  • 25,481
  • 10
  • 85
  • 128
  • This can be achieved more easily by what the OP is using: `jQuery(document).ready(function($) {...});`. – Felix Kling Nov 01 '12 at 18:32
  • @FelixKling It might or might not be easier, it is definitely not more flexible (i.e. you _have_ to use `$.ready`, which I don't need if I load my stuff at the end of the page. Also, my example is suggested by the [jQuery Plugin Authoring](http://docs.jquery.com/Plugins/Authoring) page. – fresskoma Nov 01 '12 at 18:34
  • I was talking about the scoping with regards to the DOM ready event. Plugins are a different story ;) – Felix Kling Nov 01 '12 at 18:36
  • Ah, I see. I guess I got carried that way because he was already using a similar construct in his example, and then my brain made the connection to jQuery plugins. Nonetheless, I usually encapsule all my JavaScript files that way, because even if it is not the easiest way, it is at least consistent :) – fresskoma Nov 01 '12 at 18:40