Javascript conflicts and portlet namespaces

First - javascript doesn’t actually have “namespaces”. But the idea is there - unless functions, objects and variables are designated otherwise, they exist in the global scope - properties of the window object. In a portal - where portlets might want to include script libraries to facilitate interaction within the portlet - there’s a risk of conflicts with objects using the same name being redefined by portlet-imported code. There is no “portlet scope” - it would have to be artificially defined. This is doable for instance variables, but more problematic for libraries.



Joe Walker (author of DWR - a remoting framework for javascript/java) blogs about one face of this problem here - the $ function




Conflict can exist between code in/required by different portlets on a page, or portlet code and the portal wrapper (style). The $ function is just one example of how code can compete. The other issue is that as javascript is a dynamic, prototype-based language, its quite possible for a script to change the same features of the language mid-stream:

Function.prototype.bind = function(someObjectToBindTo) {
// .. do stuff.
}

This is increasingly common as library authors seek to give developers a familiar environment to code in and add syntactical sugar for common tasks. The problem is that method signatures and return values may differ, and functionality may differ so redefinition is a real issue. This is where I think there’s a need for guidelines and accepted best practice. Defensive coding will get you around most of it.. but not all.



Finally, there’s the even thornier issue of 2 portlets using different versions of the same library. Even if the library was coded to be backward compatible, it would require a way to ensure the earlier version was not included last.