Skip to content

Adding custom JavaScript

Mark Reeves edited this page Jan 4, 2018 · 9 revisions

It is possible to add application-specific JavaScript to a WComponents application. Before doing so though one ought consider carefully whether:

  1. the functionality one is trying to implement is already available in the theme; and
  2. if not then should it be added to the theme?

Adding a cacheable JavaScript file

The most efficient way to add JavaScript is usually using a cacheable script file.

Using WApplication

WApplication has these methods which may be used to add a script element to the page head element:

  • addJsUrl(String url); and
  • addJsFile(String fileName).

Each of these methods has the same net effect: a HTML script element will be added to the head with the src set to the url or file resource. The script element is placed after the inclusion of WComponents scripts and requirejs configuration and inclusion therefore you should be able to rely on the presence of requirejs and if you build your script as an AMD module you will be able to use WComponents modules.

// Get the WApplication from the current object'
WApplication app = WebUtilities.getAncestorOfClass(WApplication.class, this);

// Then use this WApplication to add JS from a resource.
app.addJsFile("/path/to/resource/my_javascript_file.js");
// Adding from a URL is similar. Use '//'' to avoid defining the protocol.
app.addJsUrl("//example.com/path/to/static_js_file.js");

Adding inline JavaScript

Using WText

WText may be used to output any HTML element(s) including a script element. You must turn off output escaping (doing this is considered harmful) and you are completely responsible for ensuring your HTML snippet is XML compliant. This includes knowing what to escape or enclosing your script in a CDATA block.

// Let us assume we have a JavaScript snippet we want to include and it is in
// a String MY_SCRIPT which should include the script element opening and
// closing tags and a CDATA wrapper if required.
WText jsText = new WText(MY_SCRIPT);
jsText.setEncodeText(false);
add(jsText);

The script element will be echoed to the output stream (HTML) in the position in which it is added to the component tree.

Using WTemplate

Custom JavaScript may be included in a view by adding it to a WTemplate. The same caveats apply as for using WText.

Related topics

Clone this wiki locally