What is the difference in execution of code when wrapped these ways
(function($)开发者_StackOverflow社区 {
// ... code here ...
})(jQuery);
jQuery(function($) {
/// ... code here ...
});
The first one calls immediately, the second one when the DOM is loaded and ready.
In the first case, jQuery is being passed in directly and re-purposed to use the local variable $ in the method. In the first case, $ will act like jQuery as you're used to. This is often used for plugins that do not assume $ represents jQuery (since jQuery can fallback to not use $ if there is a conflict).
In the second case, jQuery is just doing that conflict protection for you, providing you with a local representation of $ that is not going to conflict with any other libraries.
The first one is also called when it is parsed, as mentioned by others. The leading parenthesis is a convention to imply that the function definition itself is followed by a open/close parentheses set - which executes immediately. The second is called on page load.
The first one is used for stealing the $ symbol when dealing with multiple frameworks, and is also used for making variable declarations local (which the latter example does as well). The latter example is used for executing scripts on page load, but can be more cleanly written as:
$(function() {
/// code
});
Check using jquery with other libraries docs as well.
jQuery(function($) {});
If you include jQuery before other libraries, you may use "jQuery" when you do some work with jQuery, and the "$" is also the shortcut for the other library. There is no need for overriding the $-function by calling "jQuery.noConflict()".
<html>
<head>
<script src="jquery.js"></script>
<script src="prototype.js"></script>
<script>
// Use jQuery via jQuery(...)
jQuery(document).ready(function(){
jQuery("div").hide();
});
(function($) {})(jQuery);
Use the following technique, which allows you to use $ inside of a block of code without permanently overwriting $:
(function($) { /* some code that uses $ */ })(jQuery)
精彩评论