16963

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.

Answer1:

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

<hr>

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.

Answer2:

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 || {}));

Answer3:

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.

Answer4:

    <li>Using $(function () {}); anytime after the document is ready is perfectly safe, the specified function will fire immediately. Quote:</li> </ul>

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

      <li>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.</li> </ul>

      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.

      Answer5:

      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.

      <hr>

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

Recommend

  • Regex: match only outside parenthesis (so that the text isn't split within parenthesis)?
  • Casting float to string without scientific notation
  • Xcode compile error on bool when device not connected
  • regex: Match at least two search terms
  • Sharing custom code between two NodeJS microservices
  • Howto count a variable inside of innerHTML?
  • Form Post with enctype = “multipart/form-data” causing parameters to not get passed
  • Prolog Query - Trying to understand how this result happens
  • Curried UDF - Pyspark
  • jersey/tomcat Description The origin server did not find a current representation for the target res
  • Magento get URL before current
  • How can I run DataNucleus Bytecode Enhancer from SBT?
  • Jquery Knockout: ko.computed() vs classic function?
  • SonarQube: Cannot deactivate rule with missing quality profile
  • How to add a focus style to an editable ComboBox in WPF
  • How do I signal completion of my dataflow?
  • Convert Type Decimal to Hex (string) in .NET 3.5
  • Diff between two dataframes in pandas
  • Parsing a CSV string while ignoring commas inside the individual columns
  • Installing iPhone App to iPhone
  • How to define and use opencv mat of user type
  • Refering to the class itself from within a class mehod in Objective C
  • Avoid links criss cross / overlap in d3.js using force layout
  • Java: can you cast Class into a specific interface?
  • Azure Cloud Service Web Role web pages do not load
  • AES padding and writing the ciphertext to a disk file
  • Updating server-side rendering client-side
  • Does CUDA 5 support STL or THRUST inside the device code?
  • How to extract text from Word files using C#?
  • SSO with signing and signature validation doesn't work
  • Deserializing XML into class C#
  • When should I choose bucket sort over other sorting algorithms?
  • How do you troubleshoot character encoding problems?
  • How to include full .NET prerequisite for Wix Burn installer
  • Understanding cpu registers
  • costura.fody for a dll that references another dll
  • Observable and ngFor in Angular 2
  • UserPrincipal.Current returns apppool on IIS
  • java string with new operator and a literal
  • jQuery Masonry / Isotope and fluid images: Momentary overlap on window resize