4 ms·
Sorry, but you're both wrong. Best practice is this: (function($) { // Plugin code }) (jQuery) And you'll see it in UI and most other good jQuery pl
by thomasmallen 18y ago
Sorry, but you're both wrong. Best practice is this:
(function($) {
// Plugin code
}) (jQuery)
And you'll see it in UI and most other good jQuery plugins.
- LogicHoleFlaw 18y agoWhat is the advantage of (function($){})(jQuery) over jQuery(function($){}) ? In either case the jQuery object must be in the namespace, and neither leaves a named function laying about. According to the jQuery API jQuery(callback) is sugar for $(document).ready(callback). The ready event is usually when I want my code to run... http://docs.jquery.com/Core/jQuery#callback http://docs.jquery.com/Core/jQuery#callback
- humanchimp 18y agoThe (function($){...})(jQuery) syntax is used by plug-in developers who want their code to run before the jQuery(document).ready event. It is closure, and it's purpose in this case is to protect the global namespace from variables introduced by the script. Closures also have many other useful applications in JavaScript.
- mncaudill 18y agoThis is one technically correct (which is usually the best kind of correct), but the jQuery() invocation has one advantage that I feel makes up for adding "jQuery" to the global namespace which is that the next person that needs to modify my javascript sees my code, they'll see the jQuery right up front and know what's up.
- thomasmallen 18y agoThat's what comments are for :^) I always make the dependency pretty clear in my scripts. Plus, it's a "best practice" in the jQuery community to name your plugins in the form jquery.plugin.js or jquery.package.plugin.js.