superlogical
superlogical

Reputation: 14950

jQuery page load

I see people using all these different techniques with jQuery. I know the 2nd technique will run on page load. But when will the 1st and the 3rd functions fire? The third technique is used in plugins to avoid conflict right? But that will fire before page load surely? I also added a 4th technique. I would like to know when you should/shouldn't use each technique. And if any of them are bogus let me know!

1st

(function($) {

})(jQuery);

2nd

$(document).ready(function(){

});

3rd

$(function(){

}());

4th

jQuery(function($) { 

}); 

5th

(function(){

})();

Upvotes: 16

Views: 8812

Answers (2)

Adam Kiss
Adam Kiss

Reputation: 11859

1st - assigns the $ to jQuery for use only inside the brackets (no conflict version) 2nd is normaln version and 3rd is shorthand :)

more: http://docs.jquery.com/Using_jQuery_with_Other_Libraries#Overriding_the_.24-function

Edit: Oh yes, the shorthand is:

$(function() {
  // your code
});

(no parenthesis after function() brackets)

Edit: After longer reading my own link, it seems, that the first one may only wrap part of code, where $ symbol is assigned to jQuery, but you still have to use $(document).ready()

Edit:As for updated list: 5th type: check the other answer, I did not know about that type.

jQuery(function($){

});

The 4th, however, is used for: 1., attach $ to jQuery, temporarily overloading (inside brackets) any framework, that has $ shorthand in use globaly (i.e. prototype) and ALSO is document.ready statement.

Upvotes: 4

Craig Stuntz
Craig Stuntz

Reputation: 126547

Update He's changed the list of calls in the question, so I'm updating to match.

The first is a hack to avoid conflicts with other libraries which might assign $. It is not a ready handler. The second and third are ready event handlers.

From the jQuery API reference:

All three of the following syntaxes are equivalent:

  • $(document).ready(handler)
  • $().ready(handler) (this is not recommended)
  • $(handler)

So although these three do the same thing, avoid the second.

In jQuery 1.3, $() was equal to $(document). This is no longer true in 1.4.

The fourth looks like a syntax error to me. It essentially assigns a new ready handler, but it passes a function with an argument called $. Since this is an event handler, jQuery will pass event info in the first argument. You don't typically want $ to represent event info.

The fifth defines a new function and then invokes it immediately, passing no arguments. So this:

(function(){
    alert("Hi!");
})();

Means the same as this:

alert("Hi!");

Upvotes: 12

Related Questions