Monday, April 11, 2011

JavaScript in Liferay Portlets! How?

So as much as I personally detest using JavaScript and prefer to handle my AJAX through ICEfaces, there are occasionally times when one absolutely must use some JavaScript. I also grudgingly admit that there are plenty of people out there for whom using JavaScript is a delight.

This post is for you.

Using JavaScript class files with Liferay portlets is easy, but it seems unusually difficult to get a simple, straightforward answer to the question "How do I link my .js files to my portlet?"

Now, the answer I've heard around the water cooler is "Stick it in the HEAD tag on your page, of course." Well if you're following best practice, your portlet has no business including a HEAD or BODY tag. Not only that, but by doing it that way you're asking for all sorts of interesting conflicts. There is a better way.

Your Liferay portlet includes, in your WEB-INF folder, a liferay-portlet.xml file, does it not?

It had better.

That's where you define your .js and .css class files for the portlet.

Inside the <portlet> element, you should have these two settings:

<header-portlet-css>
/xmlhttp/css/mysuperawesomestyle.css
</header-portlet-css>

<header-portlet-javascript>
/js/theworldsgreatestjavascript.js
</header-portlet-javascript>

With those paths and filenames being relative to the portlet's own application directory.

Have more than one file to link? Use multiple tags and define each one individually.

2 comments:

  1. Thanks. It helped me allot.

    ReplyDelete
  2. Great short and to the point post. I'm glad someone said this. It is shocking how many articles talk about modifying the head of a portal page (normally via a purpose built Liferay theme) on which a portlet is rendered in order to enable portlets to reference JavaScript / CSS. #missingthepoint

    ReplyDelete