jQuery no-conflict wrapper redux

Recently, I stumbled upon this tweet:

The jQuery wrapper format is slightly different than the one I’ve been using for the past few years. I then queried the Internet:

Here it is written a little more clearly:

(function($) {
   ...
})(jQuery);

vs.

(function($) {
   ...
}(jQuery));

Justin was kind enough to break this down for me:

“So, you’ve got this anonymous function, right?  Ok, now call it.” versus “So, you’ve got this anonymous function and you’ve called it, right?”

The results are the same, but the execution is slightly different. As I get deeper into the JavaScript world, I’m catching these differences – my eye is being trained to find these subtleties – which is both scary and awesome.

To answer Dustin’s question, yes – we do still need to use this kind of wrapper for jQuery. WordPress, specifically, still enqueues jQuery in no-conflict mode, meaning we can’t utilize the $ shortcut in our scripts without using this kind of wrapper. The wrapper serves as a namespace for our scripts, separating our code from any other scripts using the $ object for their own purposes.

3 thoughts on “jQuery no-conflict wrapper redux

Leave a Reply

Your email address will not be published. Required fields are marked *