JavaScript Namespacing in Portlets

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>
Comments:

Great article. Here is an article on how to use it with the jQuery object. In other words namespasing with the jQuery http://jquery-howto.blogspot.com/2009/01/namespace-your-javascript-function-and.html

Posted by jquery how to on January 29, 2009 at 02:28 AM MST #

Post a Comment:
  • HTML Syntax: NOT allowed
About

gregz

Search

Top Tags
Categories
Archives
« April 2014
SunMonTueWedThuFriSat
  
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
   
       
Today