Use of the $ alias in plugins
When we write jQuery plugins we, of course, must assume that the jQuery library is loaded. We cannot assume, however, that the $
alias is available. Recall that the $.noConflict()
method can relinquish control of this shortcut. To account for this, our plugins should always call jQuery methods using the full jQuery
name or internally define $
themselves.
Especially in longer plugins, many developers find that the lack of the $
shortcut makes code more difficult to read. To combat this, the shortcut can be locally defined for the scope of the plugin by defining a function and immediately invoking it. This syntax for defining and invoking a function at once, often referred to as an Immediately Invoked Function Expression (IIFE), looks like the following code snippet:
(function($) { // Code goes here })(jQuery);
The wrapping function takes a single parameter, to which we pass the global jQuery
object. The parameter is named $
, so within the function we can use the...