Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bundling Javascript into a GWT app

Tags:

gwt

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' the JS into the app itself, rather than downloading them separately via a module script include?

like image 967
Sudhir Jonathan Avatar asked Nov 20 '10 11:11

Sudhir Jonathan


3 Answers

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();
like image 111
Dennis Avatar answered Oct 31 '22 18:10

Dennis


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();
like image 33
Helpa Avatar answered Oct 31 '22 18:10

Helpa


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.

like image 2
Chris Lercher Avatar answered Oct 31 '22 19:10

Chris Lercher