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.
Using the
@JavaScript
,@JsModule
, and@HtmlImport
annotations.Example: Importing HTML and JavaScript files into
CustomComponent
.Java
@Tag("div")
@JsModule("./src/my-module.js")
@JavaScript("/js/script.js")
@HtmlImport("/html/htmlimport.html")
static class CustomComponent extends Component
implements HasText {
// implementation omitted
}
- All the resource annotations are repeatable. Add one annotation for each file you need to add.
Using the
addJavaScript(String url)
andaddHtmlImport(String url)
methods from thePage
class. ThePage
class also has methodaddJsModule(String url)
but it is meant to be used to add an external JavaScript module.Example: Using the
addJavaScript(String url)
andaddHtmlImport(String url)
methods to import HTML and JavaScript files.Java
private void addDependencies() {
UI.getCurrent().getPage()
.addJavaScript("/js/script.js");
UI.getCurrent().getPage()
.addHtmlImport("/html/htmlimport.html");
// external JavaScript module
UI.getCurrent().getPage()
.addJsModule("https://unpkg.com/lodash@4.17.15");
}
See Storing and Loading Resources for more on storing your resources, configuring advanced resource loading, and resource load ordering.