user1240207
user1240207

Reputation: 217

Difference Between jQuery Syntax

I just wonder what's the difference between these two? Sometimes, only the second version works:

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

or

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

Upvotes: 1

Views: 62

Answers (2)

T.J. Crowder
T.J. Crowder

Reputation: 1074028

There's a big difference:

  1. The first is an immediately-invoked function expression (IIFE): The contents of the function are run as soon as the function is encountered.

  2. The second registers a jQuery "ready" callback. The contents of the function aren't called until jQuery decides the DOM is "ready". It's a shorthand for ready.

In both cases, the value of the jQuery symbol is passed into the function as the $ argument, so you can use $ for jQuery within the function even if noConflict has been used. (In the first case, it's done explicitly right there in the IIFE; in the second case, jQuery does it when calling the callback.)

The reason the second one would "work" sometimes when the first wouldn't would be that the contents of the function look for elements in the DOM, which in the first case may not be there. Consider:

<script>
(function($) {
  $("#foo").on("click", /*...*/); // Doesn't find the element
})(jQuery);
</script>
<div id="foo">...</div>

When the function runs, the #foo element doesn't exist yet, and the click handler won't be attached. But if you did the ready version instead, jQuery would wait to run the contents of the function until later.

If you control where the script tags go, you don't need ready; instead, just put the script tag at the end of the document, just before the closing </body> tag, so that all the elements the code may want to use already exist when the code runs, e.g.:

<div id="foo">...</div>
<!-- ... -->
<script>
(function($) {
  $("#foo").on("click", /*...*/); // DOES find the element
})(jQuery);
</script>
</body>

Upvotes: 5

Rory McCrossan
Rory McCrossan

Reputation: 337560

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

This is a self-invoked function where you pass in jQuery as a parameter.

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

This is a shortcut for jQuery's document.ready handler.

The main difference between the two is that the code in the first example will be run immediately, the code in the second block will only be run when the DOM is ready. Therefore if you have code in the first block which depends on the existence of certain elements within the DOM, it will fail.

Upvotes: 1

Related Questions