0

What's the difference between using this

jQuery(function(){
  jQuery('ul.sf-menu').superfish();
});

and just using this?


jQuery('ul.sf-menu').superfish();

It generates the same results, so far as I can tell, but most official code references suggest the former. Can someone explain?

I read through the post What does (function($) {})(jQuery); mean?, but I'm still not certain what the difference is.

Community
  • 1
  • 1
Maxx
  • 3,536
  • 8
  • 30
  • 36

2 Answers2

4

Wrapping any function inside jQuery or $ makes sure that it executes it on document ready and not immediately.

This will initialize the plugin on document ready which will ensure the required plugin script is loaded on the page.

jQuery(function(){
  jQuery('ul.sf-menu').superfish();
});

Alternatively you can also use this

jQuery(document).ready(function(){
   jQuery('ul.sf-menu').superfish();
});

This will initialize right away once the code is parsed but it might throw an error if the plugin script is not loaded so not recommended.

jQuery('ul.sf-menu').superfish();
ShankarSangoli
  • 67,648
  • 11
  • 84
  • 121
  • so it's exactly the same as using .ready? That's good to know, I've been using both for no reason, apparently. Thank you. – Maxx Dec 29 '11 at 21:17
4

If you use the jQuery() function with a function as its parameter, then it acts as an alias for $(document).ready().

Matt Bradley
  • 4,127
  • 17
  • 11