user106197
user106197

Reputation:

Difference between jQuery code structures

What is the difference between these jQuery code structures, or is there no difference. Are they both an alias for $(document).ready(function(){ and if so, why the dollar in the first code snippet?

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

AND

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

Upvotes: 2

Views: 96

Answers (4)

BNL
BNL

Reputation: 7133

The $ parameter in the first block is unneeded in that context.

Where you would see it is in a block like this:

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

In that context it would allow you to always use the $ alias even if there was a conflicting library.

Ignoring that, there is no difference. $ is just an alias for jQuery.

Both are shortcuts for $(document).ready(function(){

Upvotes: 5

ivantod
ivantod

Reputation: 773

The first code snipped serves the purpose of avoiding conflicts with other JS libraries that may be using the $ symbol. Wrapping the jQuery code in this manner allows you to use $ inside without worrying about conflicts. It's a good practice e.g. if you are writing a jQuery plugin to protect against conflicts in this manner. Otherwise, normally jQuery is a synonym for $.

Also have a look here for some additional info on avoiding conflicts with other libraries: http://api.jquery.com/jQuery.noConflict/

Upvotes: 0

voigtan
voigtan

Reputation: 9031

if you only are using jQuery then both $ and jQuery is the same, but if you are using another javascript library that uses $ as a shortcut then they wont be the same. But if its just jQuery then its just like you and @BNL have written its, its the same.

Upvotes: 0

Andy
Andy

Reputation: 30135

What BNL said and yes, they are both an alias for $(document).ready(function(){

you could also write jQuery(document).ready(function(){ :)

Upvotes: 0

Related Questions