What is the difference between function($)
and $(function())
?
Is this code redundant?
(function($) {
"use strict";
$(function() {
run_code();
});
})(jQuery);
Are they both document ready functions?
What is the difference between function($)
and $(function())
?
Is this code redundant?
(function($) {
"use strict";
$(function() {
run_code();
});
})(jQuery);
Are they both document ready functions?
They may look similar, but they are completely unrelated.
This is called an Immediately Invoked Function Expression (IIFE). These are not specific to jQuery, but in this case, it ensures that within the body of this function, $
will refer to jQuery
, even if something outside the function has overwritten the global $
variable with something else. It is a defensive practice for minimizing conflicts with other libraries.
An additional benefit is that any variables declared within this function will not be added to the global scope. Even without jQuery, this is a common practice used to help modularize code and avoid polluting the global scope.
(function($) {
"use strict";
})(jQuery);
This tells jQuery to execute the specified function when the DOM is "ready":
$(function() {
run_code();
});