JavaScript usage in portlets requires care by the portlet developers to avoid library, version and namespace conflicts with both the portal framework and other portlets on the same page.Below are uPortal's recommendations for using JavaScript frameworks in your portlets to help mitigate these issues.
Recommended Frameworks
jQuery
A very full featured JavaScript framework that has some key features for working in a portal environment including global namespace and conflict resolution. Fluid uses jQuery as its base JavaScript framework.
JavaScript Loading
Below is an example of loading jQuery 1.4.2, jQuery TreeView 1.4.0 and assigning them under the myPortletName var with the portlet's namespace key. The myPortletName var with the portlet namespace property is used as a namespace for this portlet's JavaScript, allowing the portlet to declare its own functions without placing them in the global namespace.
<!-- Use a resource URL for common javascript libraries that multiple portlets may share and is present in the Resource Serving Webapp. --> <script src="<rs:resourceURL value='/javascript/jquery/1.4.2/jquery-1.4.2.pack.js'/>" type="text/javascript"></script> <script src="<rs:resourceURL value='/javascript/jquery-treeview/1.4.0/jquery.treeview.js'/>" type="text/javascript" ></script> <script src="${pageContext.request.contextPath}/javascript/myPortlet.js" type="text/javascript" ></script> <!-- alternate style <script src="<c:url value='/javascript/myPortlet.js'/>" type="text/javascript" ></script> --> <script type="text/javascript"> /* * Don't overwrite an existing myPortletName variable, just add to it */ var myPortletName = myPortletName || {}; myPortletName["${n}"] = myPortletName["${n}"] || {}; /* * Switch jQuery to extreme noConflict mode, keeping a reference to it in the myPortletName["${n}"] namespace */ myPortletName["${n}"].jQuery = jQuery.noConflict(true); /** * Use an anonymous function to initialize all JavaScript for this portlet. */ (function($) { // treeview init $('#${n}community ul.listing').treeview({ animated: {duration:300, easing:"swing"}, collapsed: true, unique: false }); $('#${n}community ul.treeview ul').siblings('a').click(function(e) { e.preventDefault(); $(this).siblings('div.hitarea').trigger('click'); $(this).blur(); }); })(myPortletName["${n}"].jQuery); </script>
Using this approach the portlet is ensured it will not be affected by other versions of jQuery loaded on the same page or other JavaScript frameworks that affect $. The approach is described on jQuery's Using jQuery with Other Libraries page.
If you've got your javascript in a .js file -- one that can't resolve the server-side expression '#${n}container' -- you can launch something in the .js file from within the .jsp, passing a reference to the ${n}container div.
// In a JSP file: <script> myPortletName.myObj["${n}"] = customJsLib.myCustomConstructor($('#${n}container')); myPortletName.myObj["${n}"].init(); </script>
jQuery Selectors
If you need to target an element in your markup, you must also make sure that those elements are named appropriately. In most cases your portlet is just one small part of the content on the page and it is easy to end up with id and class conflicts. The portlet API provides a <portlet:namespace/>
tag that generates a unique, JavaScript/CSS safe, string for your instance of the portlet. A common pattern for using this value is to set it as a JSP variable and use the variable in the markup and JavaScript to end up with unique IDs in the output.
<!-- Store the portlet namespace string in the JSP page variable "n" --> <c:set var="n"><portlet:namespace/></c:set> <!-- Create a message block using the namespace variable to give it a unique ID --> <div id="${n}loadingMessage" class="portlet-msg-info" role="status"> <h3><spring:message code="loading.information"/></h3> <p><spring:message code="please.wait.while.the.system.finishes.loading.the.requested.data"/></p> </div> <script type="text/javascript"> communities.jQuery(function() { var $ = communities.jQuery; //Use the namespace variable to select the div and perform a slideDown transition $("#${n}loadingMessage").slideDown(500); }); </script>
This approach will allow you to have multiple instances of a portlet on one page and each will target the correct element within the portlet. Alternately a recommended approach is to use a namespaced div to surround all portlet content as discussed on CSS Best Practices so you can target elements using the following approach without specifying id attributes on portlet page content:
<!-- Store the portlet namespace string in the JSP page variable "n" --> <c:set var="n"><portlet:namespace/></c:set> <link rel="stylesheet" href="/MyPortletWebapp/css/my_portlet.css" type="text/css"/> <div class="MyPortletWebapp" id="${n}container"> <!-- portlet content here, such as --> <div class="email-message"> <!-- content --> </div> <div> <script type="text/javascript"> communities.jQuery(function() { var $ = communities.jQuery; //Use the namespace variable to select the div and perform a slideDown transition $("#${n}container .email-message").slideDown(500); }); </script>
JavaScript Caching
The other important approach the above example takes is to fully qualify the paths to the JavaScript. The full library name, version number and packaging should be included on the URL that the script is loaded from. This allows the portlet developer to set aggressive browser caching headers for the JavaScript to reduce subsequent page load times. If a JavaScript framework is upgraded the change in the version number in the URL will ensure the new version is loaded.
Bootstrap in portlets
Portlets desiring to use Bootstrap JavaScript have an added complexity in that the Bootstrap JavaScript cannot be loaded multiple times on the page. Each portlet needs to cooperate in using either the portal's Bootstrap Javascript (if present) or a single Bootstrap JavaScript shared by all portlets. The portlet should use the following approach. This is not needed if the portlet is just using Bootstrap CSS.
<script src="//code.jquery.com/jquery-1.10.2.min.js"></script> <script type="text/javascript"> // Bootstrap javascript fails if included multiple times on a page. // uPortal Bootstrap best practice: include bootstrap if and only if it is not present and save it to // portlets object. Bootstrap functions could be manually invoked via portlets.bootstrapjQuery variable. // All portlets using Bootstrap Javascript must use this approach. Portlet's jQuery should be included // prior to this code block. var portlets = portlets || {}; // If bootstrap is not present at uPortal jQuery nor a community bootstrap, dynamically load it. up.jQuery().carousel || portlets.bootstrapjQuery || document.write('<script src="//netdna.bootstrapcdn.com/bootstrap/3.1.1/js/bootstrap.min.js"><\/script>'); </script> <script type="text/javascript"> // Must be in separate script tag to insure bootstrap was dynamically loaded. portlets["${n}"] = {}; portlets["${n}"].jQuery = jQuery.noConflict(true); // If bootstrap JS global variable was not defined, set it to the jQuery that has bootstrap attached to. portlets.bootstrapjQuery = portlets.bootstrapjQuery || (up.jQuery().carousel ? up.jQuery : portlets["${n}"].jQuery); </script>
Development Tips
Javascript aggregation tip
On your local and dev instance, you can permanently disable JavaScript and CSS aggregation by adding to your .bash_profile:
export JAVA_OPTS="$JAVA_OPTS -Dorg.jasig.resourceserver.utils.aggr.aggregated_theme=false”