2.13. Page HEAD Elements

The Page class provides the method getHeadElements() for contributing HEAD elements such as JsImport, JsScript, CssImport and CssStyle.

Here is an example of adding HEAD elements to the MyPage class:

public class MyPage extends Page {

    public MyPage() {
        // Add the JavaScript import "/mypage.js" to the page
        getHeadElements().add(new JsImport("/mypage.js"));

        // Add some inline JavaScript content to the page
        getHeadElements().add(new JsScript("alert('Welcome to MyPage');"));

        // Add the Css import "/mypage.css" to the page
        getHeadElements().add(new CssImport("/mypage.css"));

        // Add some inline Css content to the page
        getHeadElements().add(new CssStyle("body { font-family: Verdana; }"));
    }

    ...

} 

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

Below is the /my-page.htm template:

<html>
  <head>
    $headElements
  </head>

  <body>

    ...

    $jsElements

  </body>
</html> 

The two variables, $headElements and $jsElements, are automatically made available to the Page template. These variables references the JavaScript and Css HEAD elements specified in MyPage.

The following HTML will be rendered (assuming the application context is "/myapp"):

<html>
  <head>
    <link rel="stylesheet" type="text/css" href="/myapp/mypage.css"></link>
    <style rel="stylesheet" type="text/css">
      body { font-family: Verdana; }
    </style>
  </head>

  <body>

    ...

    <script type="text/javascript" src="/myapp/mypage.js"/>
    <script type="text/javascript">
      alert('Welcome to MyPage');
    </script>

  </body>
</html> 

A live demo showing how to add HEAD elements to a Page can be seen here.