Using a JavaScript library or a style sheet in an add-on

Including style sheets or JavaScript files in your add-ons or as a part of your application can now be done by adding a @StyleSheet or @JavaScript annotation to a Component or Extension class. Each annotation takes a list of strings with URLs to the resources that should be loaded on the page before the framework initializes the client-side Component or Extension.

The URLs can either be complete absolute urls (e.g. https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js) or relative URLs (e.g. redbutton.css). A relative URL is converted to a special URL that will download the file from the Java package where the defining class is located. This means that e.g. @StyleSheet({"redbutton.css"}) on the class com.example.RedButton will cause the file com/example/redbutton.css on the classpath to be loaded in the browser. @JavaScript works in exactly the same way - see Integrating a JavaScript component for a practical example.

Java

  1. @StyleSheet("redbutton.css")
  2. public class RedButton extends NativeButton {
  3. public RedButton(String caption) {
  4. super(caption);
  5. addStyleName("redButton");
  6. }
  7. }

In this simple example, the RedButton component just adds a redButton style name to a normal NativeButton. redbutton.css is located in the same folder as RedButton.java and has this content:

CSS

  1. .redButton {
  2. background-color: red;
  3. }

This new mechanism makes it very easy to include style sheet or JavaScript files with add-ons and automatically load them in the browser when the add-on is used.