jquery: help difference between domready and $(function…
hey guys, i found a very intersting website template that has in it's header file the following lines:
(function($){
$(function(){
…normal jquery
}); // end of document ready
})(jQuery); // end of jQuery name space
what does that mean? i thought if i want to use domready i hav to write:
$(document).ready(function(){
where is the difference and can i change that? 开发者_Python百科thank you for your help
$(function() {
is a just a shortcut for $(document).ready(function() {
, they are equivalent. The (function($){
.... })(jQuery);
portion is just for compatibility, so that $
is the jQuery
object inside the scope (even if it's something else outside).
Something to note here: document.ready
handlers receive jQuery
as their first argument, so the site's code could be more concisely expressed as:
jQuery(function($){
…normal jquery
}); // end of document ready
So the answer your question: do you have to change it? nope, use whichever format you prefer...I prefer $(function() { });
because it's less to type and I do it a hundred times a day. If you find $(document).ready(function() { });
much clearer, stick with that, but they behave the same...so use whichever is clearer to you and your team.
The DOM ready portion of the code you cited:
$(function() {
// Document is ready let's write some jQuery!
});
Is entirely equivalent to:
$(document).ready(function () {
// Document is ready let's write some jQuery!
});
The part that wraps the DOM ready stuff is there for a completely separate purpose:
(function($) {
...
})(jQuery); // end of jQuery namespace
The above is actually a function invocation. You're calling an anonymous function and passing in the jQuery
object as an argument, which is then assigned to the parameter $
. This ensures that all of the code inside (where I've got ...
) can use $
knowing that it refers to jQuery
.
This is a failsafe that people use because some other JavaScript code could have assigned the $
variable to something other than jQuery
within the global namspace. By wrapping your jQuery code in a function (remember -- only functions have scope in JavaScript) that assigns jQuery
to $
, you're safe.
精彩评论