Skip to content
This repository was archived by the owner on May 6, 2021. It is now read-only.

Latest commit

 

History

History
48 lines (40 loc) · 1.61 KB

File metadata and controls

48 lines (40 loc) · 1.61 KB
title order layout
Importing JavaScript
2
page

Importing JavaScript and JavaScript modules

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.

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

  2. Using the addJavaScript(String url) method 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) 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.