Importing JavaScript, JavaScript modules, and HTML

You can add classic JavaScript source files, JavaScript modules, and HTML imports (compatibility mode) to your host page directly from your Java classes.

Note
Polymer 3 templates should be imported using @JsModule (see Creating Polymer Templates for more information).

There are two ways to add JavaScript and HTML files. Both have the same effect and you can use whichever suits you best.

  1. Using the @JavaScript, @JsModule, and @HtmlImport annotations.

    Example: Importing HTML and JavaScript files into CustomComponent.

    Java

    1. @Tag("div")
    2. @JsModule("./src/my-module.js")
    3. @JavaScript("/js/script.js")
    4. @HtmlImport("/html/htmlimport.html")
    5. static class CustomComponent extends Component
    6. implements HasText {
    7. // implementation omitted
    8. }
    • All the resource annotations are repeatable. Add one annotation for each file you need to add.
  2. Using the addJavaScript(String url) and addHtmlImport(String url) methods from the Page class. The Page class also has method addJsModule(String url) but it is meant to be used to add an external JavaScript module.

    Example: Using the addJavaScript(String url) and addHtmlImport(String url) methods to import HTML and JavaScript files.

    Java

    1. private void addDependencies() {
    2. UI.getCurrent().getPage()
    3. .addJavaScript("/js/script.js");
    4. UI.getCurrent().getPage()
    5. .addHtmlImport("/html/htmlimport.html");
    6. // external JavaScript module
    7. UI.getCurrent().getPage()
    8. .addJsModule("https://unpkg.com/lodash@4.17.15");
    9. }

See Storing and Loading Resources for more on storing your resources, configuring advanced resource loading, and resource load ordering.