Why am I encapsulating a jQuery function in jQuery (function ($) {});

I came across a piece of code that looks like this:

jQuery(function($) { $('#saySomething').click(function() { alert('something'); }); }); 

I donโ€™t quite understand. Why can't I just do this:

 $('#saySomething').click(function() { alert('saySomething'); }); 
+7
source share
10 answers
 jQuery(function ($) {...}); 

- abridged version:

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

If you do not wait for the document be ready, the elements you will associate with events will not exist in dom, and events will usually not be related.

Alternatively, you can wait until the body finished loading, however this will include waiting for images that take longer to load.

In truth, you do not need to wait for document.ready . You can continue and use $('#saySomething').click(...) if you know that the element exists in the DOM:

 <button id="saySomething>Say Something!</button> <script> jQuery('#saySomething').click(...); </script> 

There is one last caveat jQuery(function ($) {...}); that you should be aware of. The $ parameter in the function is used for the jQuery alias - $ , which allows you to use the shorthand $ string inside the function without worrying about conflicts with other libraries (for example, the prototype).

If you are not waiting for document.ready , then usually see IIFE used for the jQuery alias:

 (function ($) { $('#saySomething').click(...); }(jQuery)); 
+17
source
 jQuery(function($) { 

is a shortcut to

 jQuery(document).ready(function(){ 

This waits while the document is in the โ€œreadyโ€ state where the DOM is embedded. Then jQuery scripts can work with a full page and not skip any elements.

But - you can run jQuery without it. If you are in the head of the script, you risk selecting items that have not yet been created. I used jQuery in the text of my document immediately after the elements (I) that I want to touch on, in an attempt to work with them as soon as possible. This was an unusual case, and I usually do not.

Another reason for using a ready-made function is that you can run it more than once. If you include multiple scripts or have conditional code, you can have several ready () functions. The code in each finished block is stored until the ready state is reached, and then the code is executed in the order in which it was added.

+6
source

The first example is called after the page is fully loaded. The second example starts directly (and probably a failure).

So, the first is an abbreviation for:

 $(document).ready(function(){ // Do something after the page is loaded. }); 
+2
source

This is a shorthand for "loading a document", and they used longhand "jQuery" with $ aliased inward to avoid collisions with other libraries using the $ sign.

If you do not wait for the document to load, everything can become unpredictable / inoperative. Also, if you have name collisions, everything will just explode.

+2
source

$(function() {}) is short for the jQuerys document ready function http://api.jquery.com/jQuery/#jQuery3 and http://api.jquery.com/ready/ for more information

+2
source

Copied and pasted directly from docs :

jQuery( callback ) Returns: jQuery

Description: The function that executes when the DOM load completes is bound.

 version added: 1.0jQuery( callback ) `callback` The function to execute when the DOM is ready. 

This function behaves exactly the same as $(document).ready() , because it should be used to transfer other $() operations to your page, which are dependent on the DOM ready. Although this function is technically related to the circuit, there it is actually not very useful for binding to it.

Please view the api

+2
source

This will depend on the context of the code, but JavaScript has a common design practice for encapsulating variables and methods in a namespace or module template. This code may be derived from this intention.

The rationale for the module design pattern comes down to complications with global variables and the dangers of "knocking down."

Clobbering can occur when any variable (or function) with the same name is defined twice. The second definition will override the first and, in essence, will hide it.

Thus, a rule of thumb is to wrap your code in a construct that protects your variables (and functions) from the global namespace. Douglas Crockford describes these scenarios well.

This example shows a slightly more common embodiment called "closure":

 var jspy = (function() { var _count = 0; return { incrementCount: function() { _count++; }, getCount: function() { return _count; } }; })(); 

At first he is disoriented, but as soon as you recognize him, he becomes second nature. The point is to encapsulate the _count variable as a private member in the returned object, which has two methods available.

This is powerful because the global namespace now includes only one var (jspy), not one with two methods. The second reason this is powerful is because it ensures that the _count variable can only be accessed by logic in two methods (incrementCount, getCount).

As I said, your code may be the embodiment of this rule of thumb.

In any case, it is important to know this template in JavaScript, because it opens the door to much more powerful interactions between frameworks, for example, and asynchronously loading them, for example, into AMD.

Here is a good namespace example.

In summation, there is an extended JavaScript design pattern that will help you find out, and the corresponding terms are a module pattern, a namespace pattern. Additional related terms are closure and AMD.

Hope this helps. All the best! Nash

+2
source

This jQuery(function(){...} is a shorcut for jQuery(document).ready(function(){...}) . The Ready event is fired when the DOM is ready, so you will be sure that you are not accessing that that is not yet available.

On the other hand, if you bind the click method in the same way as in the second fragment. This code will be executed immediately, so you must be sure to place it after the #saySomething .

+1
source

jQuery(function($) { ... }); - this is what prevents the execution of your code until the DOM (HTML) is fully rendered and inaccessible.

0
source

Here you will find all the information: http://api.jquery.com/ready/

0
source

All Articles