Nomit
Nomit

Reputation: 115

Why write code Jquery like this

Why write code Jquery like this?

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

Upvotes: 9

Views: 388

Answers (4)

jviotti
jviotti

Reputation: 18929

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

This type of Module pattern is very used out there. It invokes itself passing a reference to jQuery providing faster access to the variable, as it now lives in the scope of the function, and it also prevents global pollution.

The second one:

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

Runs the anonymous function once the DOM is loaded, that you make sure that everything is ready before executing any code.

Upvotes: 2

Jai
Jai

Reputation: 74738

This is called a closure to avoid conflicts with other libraries which are using $. This way you can ensure to use $ in that function with passing jQuery as a param.

(function ($) {
   $(function () {
    .......
   });
})(jQuery); //<----passing jquery to avoid any conflict with other libraries.

from the docs:

it's a best practice to pass jQuery to an IIFE (Immediately Invoked Function Expression) that maps it to the dollar sign so it can't be overwritten by another library in the scope of its execution.

This is generally used to author plugins. Read out more here

Upvotes: 14

Techie
Techie

Reputation: 45124

  • $(document).ready(function(){ ... }); or $(function(){...});

    This specify a function to execute when the DOM is fully loaded. The handler passed to .ready() is guaranteed to be executed after the DOM is ready, so this is usually the best place to attach all other event handlers and run other jQuery code. When using scripts that rely on the value of CSS style properties, it's important to reference external stylesheets or embed style elements before referencing the scripts. Read more

  • (function(){ ... })();

    That is a function which invokes itself as soon as possible when the browser is interpreting your ecma-/javascript. Therefore, its very unlikely that you can successfully act on DOM elements here. It will be executed as soon as it is encountered in the Javascript.

Read more

Similar Question

Similar Question 2

Explanation for your code

(function ($) { <--  $ is just an alias for jQuery
    $(function () {
     .......  <--- Here you can use the $ without an issue.
    });
})(jQuery); <--- This is done usually to avoid conflicts. Passing jQuery object here

If you look at the jQuery core. It says

// Expose jQuery to the global object
window.jQuery = window.$ = jQuery;

Read more

jQuery.noConflict()

Upvotes: 11

Hilmi
Hilmi

Reputation: 3441

Some other libraries also use the $ as a variable name so to assure you are using jQuery not other lib var you will pass it to a function and name it $ in that scope.

(function ($) { //<--- naming jQuery to $
   $(function () {//now we are sure that we are using $  as jQuery  
    .......
   });
})(jQuery); //<----passing jquery .

Upvotes: 1

Related Questions