Usage of ScriptInjector in GWT
gwt, java, javascript
Solution
1) `fromUrl` - creates `script` tag with specified src attribute and appends it to the page. E.g.
ScriptInjector.fromUrl("http://example.com/my-script.js").inject();
will simply produce:
<script type="text/javascript" src="http://example.com/my-script.js" />
You can host your files on the web site and inject each of them on demand
2) `fromString` - creates `script` tag with specified body of the script, so: ScriptInjector.fromString("alert('Injected!')").inject(); will give
<script type="text/javascript">
alert('Injected!')
</script>
In this case JS code is a part of your compiled GWT code and browser doesn't require to load it with separate request. I think it is possible to include native JS file into compiled output with `TextResource`. So you need following:
Define resources
public interface JsResources extends ClientBundle {
final JsResources INSTANCE = GWT.create(JsResources.class);
@Source("first.js")
TextResource firstScript();
@Source("second.js")
TextResource secondScript();
}
Inject required script
ScriptInjector.fromString(JsResources.INSTANCE.firstScript().getText()).inject();
Problem
I want to use javascript library in java source code. I read sth about it and I read, that I should use `ScriptInjector`. This class has 2 inner classes: `ScriptInjector.FromString` and `ScriptInjector.FromUrl`. I want to load javascript library from local file, so I should use from string. How to do it? ``` ScriptInjector.fromString("myLibrary.js"); ``` does not work. Where to add library?