0

There are multiple ways of writing document ready event in jQuery. So which one from the following syntax is more correct way of writing document ready event and why.

1)

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

2)

jQuery(function(){
});

3)

jQuery(function($){
});
Irvin Dominin
  • 30,819
  • 9
  • 77
  • 111
Aditya Singh
  • 9,512
  • 5
  • 32
  • 55
  • see here http://stackoverflow.com/questions/3512445/document-ready-or-function-which-to-use – PSR May 28 '13 at 05:18

7 Answers7

1

I think it will

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

});

This avoids conflicts with other libraries

See for reference

alwaysLearn
  • 6,882
  • 7
  • 39
  • 67
0

I've always used #1 and it works every time because only that one even calls the .ready function.

Phillip Berger
  • 2,317
  • 1
  • 11
  • 30
0

$(handler) but it doesn't really matter

royB
  • 12,779
  • 15
  • 58
  • 80
0

$(document).ready(function(){ }); is the most common and recommended way. Additional benefit is clarify for others modifying the code in the future.

partial source: http://api.jquery.com/ready/

kushyar
  • 1,191
  • 1
  • 6
  • 10
0

All three syntaxes are equivalent, but looking at the jQuery docs the version:

jQuery(document).ready(function($) {
  // Code using $ as usual goes here.
})

avoids namespaces difficulties on the $ because:

Aliasing the jQuery Namespace

When using another JavaScript library, we may wish to call $.noConflict() to avoid namespace difficulties. When this function is called, the $ shortcut is no longer available, forcing us to write jQuery each time we would normally write $. However, the handler passed to the .ready() method can take an argument, which is passed the global jQuery object. This means we can rename the object within the context of our .ready() handler without affecting other code:

Irvin Dominin
  • 30,819
  • 9
  • 77
  • 111
0

2nd is the sort form of 1st sentence

Experienced developers sometime using 2nd way

If you are writing code that people who aren't experienced with jQuery may see, it's best to use the 1st one.

Rakesh Singh
  • 1,250
  • 9
  • 8
0

If the script is in dependency, the more correct way could be:

(function(doc,win,$){
    $(doc).ready(function($){
    //do something
    });
})(document, window, jQuery);
Thomas Fenzl
  • 4,342
  • 1
  • 17
  • 25
  • Hi, welcome at stackoverflow. Your answers are easier to read (and more likely to get upvoted) if you format them correctly. I've done that for now, please think of it in the future. – Thomas Fenzl May 28 '13 at 05:47