3 super simple ways to keep your jQuery code safe

3 super simple ways to keep your jQuery code safe

If you are developing code for free distribution or developing plugins for sale, it is always recommended to consider the possibilities of name/id conflict. Think about the situation, if some other scripts imported after yours, that also contains a $ function like jQuery? To avoid that kind of issue, you can either call jQuery’s noConflict(), or to store your code within a self-invoking anonymous function, and then pass jQuery to it. This way, we can keep our code safe. Here goes 3 super simple ways to keep the jQuery code safe.

– Using NoConflict Method:

Most super simple way to avoid conflict is to use noConflict() function. Be careful with this method, and try not to use it when distributing your code. It would really confuse the user of your script!

var j = jQuery.noConflict();  
//Instead of $, we use j or any other word as you want.
j('#someDiv').hide();  

// The line below will reference some other library's $ function.  
$('someDiv').style.display = 'none';

– Passing jQuery Reference

The final parameter at the bottom call the function automatically– function(){}(). However, when we call the function, we also pass jQuery, which is then represented by $.

(function($) {  
// Within this function, $ will always refer to jQuery  
})(jQuery);

– Passing $ via the Ready Method

jQuery(document).ready(function($) {  
     // $ refers to jQuery  
});  

//$ is either undefined, or refers to some other library's function.

Was this information useful? What other tips would you like to read about in the future? Share your comments, feedback and experiences with us by commenting below!

Total 0 Votes
0

Tell us how can we improve this post?

+ = Verify Human or Spambot ?

Leave a Comment

Back To Top