Bundling Javascript into a GWT app
I'm writing an app in GWT (mapfaire.com) which uses the Google Maps API, and I'd like to use the utilities library. Writing a JSNI wrapper for the libraries isn't a problem, but how do I ensure the compiler 'bakes' 开发者_C百科the JS into the app itself, rather than downloading them separately via a module script include?
You could define a ClientBundle for your JavaScript resources like this:
public interface JsResources extends ClientBundle {
final JsResources INSTANCE = GWT.create(JsResources.class);
@Source("myAwesomeJavaScript.js")
TextResource myAwesomeJavaScript();
}
and include it in your app with the ScriptInjector:
ScriptInjector
.fromString( JsResources.INSTANCE.myAwesomeJavaScript().getText() )
.inject();
In gwt 2.4 added ScriptInjector http://gwt-code-reviews.appspot.com/1451818/
ScriptInjector.fromUrl("http://example.com/foo.js").setCallback(
new Callback<Void, Exception>() {
public void onFailure(Exception reason) {
Window.alert("Script load failed.");
}
public void onSuccess(Void result) {
Window.alert("Script load success.");
}
}).inject();
If the license allows you to do so, then you could copy and paste the entire JS code of the library into a JSNI method.
You can also use a TextResource like this:
public static interface Resources extends ClientBundle {
@Source("some.js")
TextResource someJs();
}
public void onModuleLoad() {
final Resources resources = GWT.create(Resources.class);
eval(resources.someJs().getText());
}
private static native void eval(String s) /*-{
eval(s);
}-*/;
The text of "some.js" will be interned directly into the resulting application. There won't be any separate download.
Is the gwt-maps-utility project useful for your needs?
精彩评论