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(){
})();
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 areadyhandler. The second and third arereadyevent handlers.From the jQuery API reference:
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:
Means the same as this: