The Vaadin Dynamic JavaScript Loader enables the import of JavaScript libraries from the Java classpath, web resources, and external URLs. It particularly supports integration with cloud services like cdnjs and unpkg in Vaadin applications.
This tool serves as a complementary feature to Vaadin's @JavaScript
annotation, with several key benefits:
-
Built-in Bookkeeping: Ensures a library is loaded only once per UI and checks the version.
-
URL Template-Based Syntax: Allows atomic loading of multiple files or resources from a single library.
-
Fully Dynamic Loading: Enables runtime configuration and loading for greater flexibility.
-
Load Script from Classpath: Unlike
@JavaScript
, which only supports web resources, this tool can also load scripts from Java resources and the classpath. -
Component Subclassing: Due to its dynamic nature, it is possible to modify and override loading behavior in Java component subclasses, particularly useful for updating JavaScript libraries.
-
Built-in CDN Support: Supports loading from cdnjs.com and unpkg.com, ideal for quick prototyping.
-
CSS Loading Support: Capable of importing CSS resources from the same library, in addition to JavaScript.
<dependency>
<groupId>org.parttio</groupId>
<artifactId>vaadin-js-loader</artifactId>
<version>2.2.1</version>
</dependency>
Example loading three.js from unpkg.com:
String library = "three";
String version = "0.158.0";
JSLoader.loadUnpkg(ui, library, version);
Example loading jquery from cdnjs.com:
String library = "jquery";
String version = "3.7.1";
JSLoader.loadCdnjs(ui, library, version);
Example usage loading script and css file from Java classpath. Typically in src/main/webapp
.
String library = "mylib";
String version = "1.0";
String file = "mylib.js";
String urlPattern = "/{library}-{version}/{file}";
JSLoader.loadFiles(ui, urlPattern, library, version, file);
In this case URL pattern points to folder src/main/webapp/mylib-1.0
which contains the specified resources.
Example usage loading script and css file from Java classpath. Typically in src/main/resources
.
JSLoader.loadJavaResource(ui, MyClass.class, "myScript","myscript.js", "myscript.css");
For example in a Maven project if the MyClass.java
is in package org.vaadin.example
then the files are loaded from folder src/main/resources/org/vaadin/example
.