title | order | layout |
---|---|---|
Importing JavaScript |
2 |
page |
You can add classic JavaScript source files and JavaScript modules to your host page directly from your Java classes.
Note
|
Lit templates should be imported using @JsModule (see Creating a Simple Component Using the Template API for more information).
|
There are two ways to add JavaScript files. Both have the same effect and you can use whichever suits you best.
-
Using the
@JavaScript
and@JsModule
annotations.Example: Importing JavaScript files into
CustomComponent
.@Tag("div") @JsModule("./src/my-module.js") @JavaScript("/js/script.js") 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)
method 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)
method to import JavaScript files.private void addDependencies() { UI.getCurrent().getPage().addJavaScript("/js/script.js"); // 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.