I’m shipping socket.io as part of my code for 3rd party sites to use. I don’t want it to pollute the global namespace (e.g. different versions of io will collide) but rather make it work only as part of my library, So it will be namespaced and called only from
MyLibrary.io
How do I go about this?
Since you have total control over the file, then the easiest thing to do would be to just modify the file to load socket.io at a new location.
The easiest way I would say to do that would be to wrap the contents of
dist/socket.io.jswithThat will make the file load
ioontoMyLibraryinstead. SocketIO, like many libraries, usesthisto decide how to load things. In a browser circumstance,thisis the objectwindow, but by wrapping a function around everything, you can controlthisand change it to your own value by using the methodcall.Many other libraries, though not socketIO, have a helper to avoid exactly this problem. Often they have a method called
noConflict(). For example, if you wanted to avoid a problem like this for jQuery, you could do:That works because when jQuery loads, it saves a reference to the previously loaded version, so that if it needs to, it can set the global objects back to how they were.