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’s always important to consider for any possible name/id conflict. What would happen if some script, imported after yours, also had a $ function like jQuery?

Most common answer is to either call jQuery’s noConflict(), or to store your code within a self-invoking anonymous function, and then pass jQuery to it. It’s bit nasty and will create problem in your future development. So, We need to know how to keep your code safe.

Today I’m going to share 3 super simple ways to keep your code safe. Let’s go-

– Way 1: Using NoConflict Method:

Most super simple way to avoid conflict. 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';

– Way 2: 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);

– Way 3: 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!

Share It

Related Posts