Liferay: ways to import Javascript files

In Liferay you have multiple ways to load a Javascript file. Depending on what you need to do you should use the right way.

JS that is available in ALL pages

You can reuse the mechanism that Liferay uses for loading a lot of JS files at every page load.

  • Create a hook that will add your JS file in ROOT webapp
  • Add the path to your blabla.js file to one of those properties:
    • javascript.everything.files : when user is logged in
    • javascript.barebone.files : when user is logged in / off

More details about how Liferay implemented it

JS that is specific to a theme

No suprises here, if you need to have some javascript depending on your theme (for example a specific visual effect related to current style), you need to put it in your theme 🙂

  • Put your blabla.js in the folder “js” of your theme
  • Import your blabla.js file in Velocity template “portal-normal.vm” using HTML “script” tag

If you need to use the JS in multiple themes, use theme inheritance mechansim.

JS that is specific to a portlet

In every portlet you will surely need to write some JS to do some client validation or some visual logic.

  • Put your blabla.js in the folder “js” of your portlet
  • Import the JS file at top/bottom of the portlet (depending if you need the script to be executed at the beggining/end of the displaying of the portlet page)

Side note: always try to avoid inline Javascript in your HTML.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s