How to avoid javascript namespace conflict?

喜你入骨 提交于 2019-12-06 12:53:52

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!