Difference between (function($) {})(jQuery) and jQuery(function() {}); -
i have jquery plugin minified , located @ bottom of script, , 1 of functions called somewhere in middle of script on page load.
now method 1 generates error, please see next simplified code
class="lang-js prettyprint-override">//method 1: reddish not function! /* (function($) { $("#foo").red(); })(jquery); */ // method 2: works jquery(function() { $("#foo").red(); }); // plugin (function($) { $.fn.red = function() { homecoming $(this).css("color", "red"); }; })(jquery);
can explain difference between these 2 methods? causes error in method 1?
the main difference between 2 sec 1 waits dom ready wrapping code with:
$(function(){ // code in here executed 1 time dom ready });
and plugin has time "register itself" don't error saying red
not function.
if want first version wait dom ready, utilize this:
(function($) { // $ jquery, prevents name collision other frameworks $(function(){ // register code fire after dom ready $("#foo").red(); }); })(jquery); // passes jquery parameter $ jquery
as side note, register plugins right after load jquery , these problems go away.
jquery jquery-plugins syntax
No comments:
Post a Comment