Skip to content Skip to sidebar Skip to footer

JQuery Alias For Script Specific

Wordpress ships jQuery in safe mode, this is very awesome, but a 3rd party script that I must use uses the $ alias, so there's a way of alias $ to jQuery only for that script ? (ca

Solution 1:

wrap the initialisation of the plugin in an IIFE

(function($){
   $('.some').pluginUsingDollarAsJQuery();
})(jQuery)


As per the help pages for plugin authorship:

The $ variable is very popular among JavaScript libraries, and if you're using another library with jQuery, you will have to make jQuery not use the $ with jQuery.noConflict(). However, this will break our plugin since it is written with the assumption that $ is an alias to the jQuery function. To work well with other plugins, and still use the jQuery $ alias, we need to put all of our code inside of an Immediately Invoked Function Expression, and then pass the function jQuery, and name the parameter

Which basically boils down to the fact that whoever has written the plugin you're using has not done it right.

Writing a plugin like this:

$.fn.doSomething = function(){
   // whatever
}

Will make it not compatible with anyone using jQuery in noConflict mode. It should be wrapped in an IIFE like this:

(function($){
    $.fn.doSomething = function(){
       // whatever
    }
})(jQuery)

If your plugin is the former style, ditch it.


Solution 2:

Jamiec's answer is the clean solution which should be used if you have access to the code, but in case you do not have access to it, there is a dirty solution.

You can reassign $ to jQuery just before the script is loaded. So when the script is initializing, $ === jQuery.

To do it when the script is inline in the DOM, just open a script tag for the reassignment before :

<script>$=jQuery;</script>
<script src="external_script"></script>

If you load dynamically the script (ex : jQuery.getScript), you can reassign just before calling the async function :

window.$ = jQuery;
jQuery.getScript('external_source');

WARNING : this method can break your script if window.$ was used elsewhere. It may also not work if the script is loaded asynchronous if, meanwhile, another script reassign $ to something else.


Post a Comment for "JQuery Alias For Script Specific"