To make sure that $ is always referencing jQuery, I code in this format:
Method #1
(function($) {
// Use $ here
})(jQuery);
As per my understanding, the function we created is called immediately and we are passing jQuery to it and catching it in $ so our $ will always reference to jQuery. Safest way, jQuery plugins are coded this way.
Now, I see some developers coding in the following format, which appears to work just fine but wanted to confirm if its correct & safe because I don’t understand how it can work fine.
Method #2
jQuery(document).ready(function($) {
// Use $ here
});
So, in this method, document ready function is called by directly using jQuery which is OK, but then $ is passed to it and now there is no means by which we can be sure it will reference to jQuery only, correct? Like Prototype was loaded after jQuery on page, then this $ will reference to prototype instead of jQuery inside it.
So, in a nutshell, are both methods safe? If yes, how and which one is better?
Both are safe; jQuery will pass itself as the argument to the function passed to
ready.They are both appropriate for different things. The first one is more appropriate when you want the code to execute immediately rather than waiting for the document to be ready. The latter is more appropriate when you want to execute code when the document is ready.