I have an enterprise app that imports some java script library (let's say A) with some functions in global namespace.
Our customers can extend our platform and import jquery and that will result in namespace collision.
What is best way for me to help customers not to hit namespace conflict since jquery is quite popular and every customer will be using it.
How can I change namespace of library A ? What is the most convenient and safest way to do that.
For jQuery, the easiest thing is to use jQuery.noConflict() to get a new selector variable instead of $.
var j$ = jQuery.noConflict();
j$('#test-id')
You should be building an interface that doesn't allow your customers to affect the global space.
Wrap your customers' code in its own function.
(function () {
var window, global; // Keep these private to this function
// Customer code here
])();
You will need to provide an interface for them to access your functions, but how you do that is dependent on your application, so I cannot provide an example. It might be as simple as passing in a parameter that gives access to an object that contains what needs to be manipulated by that customer code.
Now, this won't work for everything. Obviously, you are greatly limiting what their code has access to. You will need to provide access to that functionality yourself.
Use this construct:
(function ($, a, b) {
// ... place your code here
})(jQuery, myLibraryA, otherLibraryB);
It is so called "anonymous function", that creates a local scope (all variables and functions declared inside will be local and won't interfere with other code). It imports three libraries, jQuery, myLiberayA and otherLibraryB, and in local scope they are visible under names $, a and b.
you could also do this if you want to use a combination of third-party javascript libs: basically create another namespace for each object;
if(window.jQuery && !(window.MyjQuery)){
var window['MyjQuery'] = window.jQuery;
var j$ = window['MyjQuery']; //alias
j$(document).ready(function(){
//code goes here...
});
}
AdSafe might also be interesting for you, see http://www.adsafe.org/ for more info.
Good Luck
来源:https://stackoverflow.com/questions/15666634/how-to-avoid-javascript-namespace-conflict