3.5. Control HEAD Elements

The Control interface provides the method getHeadElements() which allows the Control to add Page HEAD elements such as JsImport, JsScript, CssImport and CssStyle.

Here is an example of adding HEAD elements to a custom Control:

public class MyControl extends AbstractControl {

    public MyControl() {

        /**
         * Override the default getHeadElements implementation to return
         * MyControl's list of HEAD elements.
         *
         * Note that the variable headElements is defined in AbstractControl.
         *
         * @return list the list of HEAD elements
         */
        public List getHeadElements() {

            // Use lazy loading to only add the HEAD elements once and when needed.
            if (headElements == null) {

                // Get the head elements from the super implementation
                headElements = super.getHeadElements();

                // Add the JavaScript import "/mycontrol.js" to the control
                headElements.add(new JsImport("/mycontrol.js"));

                // Add the Css import "/mycontrol.css" to the control
                headElements.add(new CssImport("/mycontrol.css"));
            }
            return headElements;
        }
    }

    ...

} 

In the example above we added the HEAD elements by overriding the Control's getHeadElements method, however you can add HEAD elements from anywhere in the Control including the event handlers onInit, onGet, onPost, onRender etc. Please see getHeadElements() for more details.

MyControl will add the following HEAD elements to the Page HEAD section, together with HEAD elements added by the Page and other controls (assume the application context is "/myapp"):

<html>
  <head>
    <link rel="stylesheet" type="text/css" href="/myapp/mycontrol.css"></link>
  </head>

  <body>

    ...

    <script type="text/javascript" src="/myapp/mycontrol.js"/>

  </body>
</html> 

A live demo showing how to add HEAD elements from a custom Control can be seen here.