2

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

4 Answers 4

5

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

Sign up to request clarification or add additional context in comments.

1 Comment

"The $ parameter in the first block is unneeded in that context." Is it ever needed, or can you always ommit it? I'm just asking cause I saw it somewhere and I never saw it like that, normally it's just jQuery(function(){
0

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

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

Comments

0

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.

Comments

0

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/

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.