I’m reading up on jQuery plugins, and in the official guide the author states:
“But wait! Where’s my awesome dollar sign that I know and love? It’s still there, however to make sure that your plugin doesn’t collide with other libraries that might use the dollar sign, it’s a best practice to pass jQuery to an IIFE (Immediately Invoked Function Expression) that maps it to the dollar sign so it can’t be overwritten by another library in the scope of its execution.”
Here is the example code:
(function( $ ) {
$.fn.myPlugin = function() {
// Do your awesome plugin stuff here
};
})( jQuery );
My question is, why is the IIFE necessary, and what are some examples of collisions that could occur without it? Upon execution, the $ parameter will be replaced by the Jquery global variable, and therefore a global variable is being altered by the IIFE. To me, that seems to suggest that collisions are just as likely as before. I know I’m missing something here. Many thanks in advance for your help!
The
$symbol is used as a global variable by other libraries such as prototype and MooTools. Therefore the$global variable might not refer to jQuery; this is the reason jQuery’s noConflict method exists.So if your plugin was to be used on a page that utilizes either prototype or MooTools in addition to jQuery, you cannot be sure that
$will be referring to jQuery, but you can assume that thejQueryvariable will. If you’re writing a plugin you want to make it as easy as possible for others to use. Therefore you want to make it seamless for use with other libraries.The IIFE makes it possible to have this safety and still have the convenience of using
$in your code. If you’re fine always referring to the jQuery library with thejQueryreference instead of$then the IIFE is unnecessary.