RSS

Safer Way of using JQuery – $ Sign to Avoid Conflics with Other Libraries

30 Apr

Due to dynamic nature in variable declarations and usage in JavaScript it is very easy that one of your variables get overwritten by scripts in other locations. This is very common for global variables so you must avoid using global variables. Many senior developers avoid using global variables but when using JQuery many unaware that they are using $ sign which is a large global variable. However there might be custom libraries or custom script files that use $ sign for their functional object roots.
Much safer option when using JQuery is to use “noConflict” method which will overcome this problem.
You can use the code like following to live with scripts that use $ sign for their own purpose.

jQuery.noConflict();
(function( $ ) {
  $(function() {
    // More code using $ as alias to jQuery
  });
})(jQuery);

Here is what the above code does.
During JQuery initialization it will do a sort of backup of “$” sign named object if there is already a one defined. So in this case if you had another library that use $ sign that object will be internally preserved when after JQuery initialized. So to restore the $ sign back you can use jQuery.noConflict();
This will essentially reverts $ sign to other library but which also introduces another annoyance. You are most likely not willing to use “jQuery” instead of much succinct “$” sign when scripting. So to avoid that you can use following technique which will again remap $ sign to JQuery but inside the anonymous function scope but not in the global window scope. So this will allow to use $ in JQuery scripting as usual.

 (function( $ ) {
  $(function() {
    // Jquery coding using $ as alias to jQuery without polluting global $ 
  });
})(jQuery);

Remember this code will also restore $ sign of JQuery itself if your output has accidentally referred multiple JQuery files or multiple versions of JQuery.

Advertisements
 
Leave a comment

Posted by on April 30, 2014 in Javascript, jQuery

 

Tags: ,

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

 
%d bloggers like this: