Docs

Documentation versions (currently viewingVaadin 14)

You are viewing documentation for an older Vaadin version. View latest documentation

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).
Note
HTML imports are no longer supported from Vaadin 14.12 onwards.

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.

    @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.

  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.

      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.

C567F89C-9DD2-4652-AA4C-BBA762BEC5B8