Wednesday, 3 October 2012

Understanding GWT Code Splitting

Problem Background
In traditional desktop application like Word Processor, there are so many features of that application that we don’t normally use. For instance, the Mail Merge tool within Word Processor is extremely useful when it's needed, but for others it may not be. So the question is how do we load only the functionality that will be used?

GWT Solution

The solution of GWT for this important issue is a concept which is called Code Splitting. In general, GWT framework provides a mechanism to split our code into segments in a way that each segment will be downloaded only when needed.

GWT.runAsync(RunAsyncCallback callback) is the method for code splitting, which will create a ‘split point’ in the code, and everything beyond that split point will be downloaded only on demand.


eg
HelloCodeSplitting.java


public class HelloCodeSplitting implements EntryPoint {
   public void onModuleLoad() {
      Button b = new Button("Click me", new ClickHandler() {
      public void onClick(ClickEvent event) {

         RunAsyncCallback callback = new RunAsyncCallback() { //#1 Creates callback
             public void onSuccess () { //#2 Defines success handler
                     Window.alert("Hello, AJAX");
        }
         public void onFailure (Throwable reason) { //#3 Defines error handler
                      Window.alert("Code download failed");
       }
       };
        GWT.runAsync(callback); //#4 Loads and executes
   }//end of onclick
  RootPanel.get().add(b);
  }//end of moduleload
}//end of Class


In GWTP
GWTP takes care of calling GWT.runAsync, whenever the corresponding Presenter is shown. But need to use AsyncProvider in the Ginjector .
So, I can achieve the same thing in gwtp framework as follows :

HelloCodeSplittingGinjector.java

@GinModules({ HelloCodeSplittingModule.class })
public interface HelloCodeSplittingGinjector extends Ginjector {
  PlaceManager getPlaceManager();
  EventBus getEventBus();
  AsyncProvider<HelloCodeSplittingPresenter> getHelloCodeSplittingPresenter();
}


HelloCodeSplittingPresenter.java

  @ProxyCodeSplit
  @NameToken("main")
  public interface HelloCodeSplittingProxy extends ProxyPlace<HelloCodeSplittingPresenter> {
  }





References
1 - http://www.javabeat.net/2011/11/code-splitting-in-gwt/

2 - http://stackoverflow.com/questions/8652534/gwtp-code-splitting

3 - http://www.summa-tech.com/blog/2011/05/03/a-pattern-for-gwt-code-splitting/

4 - https://developers.google.com/web-toolkit/doc/latest/DevGuideCodeSplitting#patterns

5 - http://benbracha.wordpress.com/2012/05/04/gwt-code-splitting/

6 - http://jcheng.wordpress.com/2010/02/16/elegant-code-splitting-with-gwt/

7- Doloto: Code Splitting for Network-Bound Web 2.0 Applications,  http://research.microsoft.com/apps/pubs/default.aspx?id=70518

No comments:

Post a Comment