Tristan
Tristan

Reputation: 6906

Avoiding polluting the global namespace with javascript dependencies

I'm building a javascript library and would like to bake in various dependencies (e.g, jQuery, Google Closure, etc) without polluting the global namespace. This is particularly important because others may already be using different versions of these libraries.

As far as I can tell most of these libraries attach themselves directly to the window object, so I cannot simply put them in an anonymous function.

Are there any general solutions to this problem?

Upvotes: 3

Views: 656

Answers (1)

typeof
typeof

Reputation: 5922

I believe you would need to modify the library source code to be able to do this, replacing their code:

window.jQuery = function(){ ... }

with:

myNamespace.jQuery = function() { ... }

Any any reference to the global jQuery object (and alias) would have to be namespaced, too. Similar measures would have to be taken for each JS library.

In my opinion, this is too much trouble for what it's worth. Taking up a single global variable for each js library is acceptable.

Upvotes: 2

Related Questions