-
Notifications
You must be signed in to change notification settings - Fork 17
Adding custom JavaScript
It is possible to add application-specific JavaScript to a WComponents application. Before doing so though one ought consider carefully whether:
- the functionality one is trying to implement is already available in the theme; and
- if not then should it be added to the theme?
The most efficient way to add JavaScript is usually using a cacheable script file.
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");
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.
Custom JavaScript may be included in a view by adding it to a WTemplate. The same caveats apply as for using WText.