Loading Resources

I’m trying to import a javascript file in my Spring Boot/Vaadin project. I have tried every possible way but nothing works. I have created the following directories:

root/frontend/src/script.js
root/src/main/frontend/src/script.js
root/src/main/resources/META-INF/resources/src/script.js
root/src/main/resources/static/src/script.js

I’m including it this way @JavaScript(“./src/script.js”) in the view and executing it this way getElement().executeJs(“jsmethod()”);

What am I missing here?

root/src/main/frontend/src/script.js should be the right location. Check that it’s getting loaded with the highly advanced alert("here") debugging technique :slight_smile:

If it is, how are you defining the function?

Maybe this could help: Vaadin 14 - difference between `@JsModule` and `@JavaScript` in npm mode – Martin Vysny – First Principles Thinking . In short, probably the best way is to use the window.test solution mentioned in the blog post.

I’ve typically used @JsModule or @JavaScript with:

  • src/main/resources/static/script.js (Spring Boot location)
  • src/main/webapp/script.js (WAR resources)
  • frontend/script.js or src/frontend/script.js (Vaadin locations)

But if you want to go dynamic or load from Java classpath, I’ve tried that easier with vaadin-js-loader. Basically allowing helper to load JavaScript from different places at runtime. Also useful if you want to allow e.g. overriding the JS library version later in inherited classes (which you cannot do with annotations).

See: GitHub - parttio/vaadin-js-loader: Dynamic JavaScript loader for Vaadin

But if you do not need the dynamic loading, the annotations should be ok. Just know the small differences Martin well described.