Handling naming conflicts in javascript libraries

When using code or plugins written by third parties, a programmer may encounter naming collisions. This condition is produced by two pieces of code attempting to give the same name to two different objects. As an example, I've personally come across a conflict between jQuery.ui and jQuery.tools. Both libraries contain a jQuery function named "tabs." The solution I came up with is to rename one of the conflicting functions.

In javascript, all objects are associative arrays. That is to say, each method or property an object contains can be thought of as a key-value pair. So window.location.href can be expressed as window[location][href], where location is the key name of an object inside the window object and href is the key name of an object inside the location object. In the third party libraries I was using, both tried to create an object named "tabs" inside the jQuery.fn object.

Each plugin tried this:

  
$.fn.tabs = function(some, parameters) {/* plugin code goes here */}

Where "$" is shorthand for jQuery.

What happens is that the included javascript is parsed in order and the last statement to define "tabs" via "$.fn.tabs = X" sets the value of "tabs." If we understand this, we can leverage it to solve our problem. What I did was to create a new jQuery function and assign the value of one of the conflicting functions to this new object.

Create a js file (I named mine fixTabs.js), and include the following:

  
$.fn.uitabs = $.fn.tabs;
delete $.fn.tabs;  

What this does is takes the tabs() function already defined by the first library included and renames it. When the second library defines the tabs() function the first is kept under it's new name (in this case "uitabs", but it can be named whatever you like).

You must include the fix js file between the script tags of the two libraries and remember that the first will be renamed. In this example I am first including the jQuery.ui library, then the fix script, then the jQuery.tools library.

You can then call:

  
$("#tabs").uitabs(); 
$(".tabs").tabs(); 
»