One of the topics that has come up a couple times while here at JavaOne is JavaScript namespacing. There was a JavaScript "Best Practices" BOF last night where it was discussed and during our "Dynamic Portals" BOF it was again discussed. In particular, the problem is that if you have multiple portlets on the same page trying to load the same JavaScript namespace (for a particular JS library, for instance
dojo.*) there will be a conflict because the namespace may already be taken (by a portlet that has already loaded it). The polite way to handle this in your portlets is to check first to see if the namespace for your library is already defined. If so, use it. If not, then dynamically load the library.
Namespacing in JavaScript is simply achieved by specifying a named object and defining all your functions relative to that object. In the case of DOJO, the object is
dojo. As you see in the below
code sample from the AJAX Portlet, you simple check for the existence of the dojo object. If it does not exist, we define a <script> element with the reference to the DOJO library and insert it dynamically into the DOM. The AJAX Portlet war is here and the source is here.
<div id="<portlet:namespace/>_scripts">
<script type="text/javascript">
/* Load Dojo library, if it hasn't already */
if (typeof dojo == "undefined") {
/* build script tag */
var script = document.createElement("script");
script.src = "<%=renderResponse.encodeURL(renderRequest.getContextPath() %>" + "/js/dojo.js";
script.type= "text/javascript";
/* dynamically insert with other scripts */
var <portlet:namespace/>_scripts = document.getElementById("<portlet:namespace/>_scripts");
<portlet:namespace/>_scripts.appendChild(script);
}
</script>
</div>

Thanks goes out to all that were able to attend last night's JavaOne BOF,
"Dynamic Portals and Ajax in Portlets". There was lots of good open discussion about the challenges and successes of implementing new dynamic portals with AJAX. The
slides are available here. Below is a list of resources URLs for some of the topics we discussed. Check back here for new developments regarding AJAX in portals and portlets.
- Portals/Portlets
- AJAX
- Widget Standards
- Microformats
- COMET
- Mashups