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 r开发者_开发知识库ight? 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(){
})();
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!");
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.
精彩评论