3

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.

5 Answers 5

3

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')
Sign up to request clarification or add additional context in comments.

Comments

2

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.

1 Comment

What's the point of declaring window & global in your anonymous function? Won't the local scope still be able to see the global attributes such as window, etc...?
2

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.

1 Comment

so see how this works for using different jQuery versions, see this post
1

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...
  });

}

Comments

0

AdSafe might also be interesting for you, see http://www.adsafe.org/ for more info.

Good Luck

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.