Friday, June 19, 2009

GWT and Google Visualization API - Tip

Google Visualization is an excellent API for adding graphing capabilities to any web application. Recently a GWT wrapper has been released which makes it easy to embed this API into GWT applications. The GWT module is really a wrapper around the standard Visualization JavaScript libraries and in order for everything to work the documentation says the following line is required in your GWT module:

<script source="http://www.google.com/jsapi"/>

With this line in place everything does indeed work, however I recently discovered a problem. Adding this line into the GWT module has the unfortunate side effect of the script element appearing in the GWT bootstrap code; the result of which is the browser will fetch the JSAPI library before actually loading your GWT module. Under normal circumstances, (ie when connected to the Internet), this isn't a problem, however this JavaScript fetch can cause significant delays if your using GWT hosted mode, or even offline, (only a small part of the application is concerned with graphing so if this library isn't loaded it's no big deal).

The Solution

The solution is not to add the script to the module definition, but instead to add it programmatically when the module is loaded. The following code shows how this issue was solved:

 public void onModuleLoad() {
  addGoogleJSAPIScript();
 }

 private void addGoogleJSAPIScript() {
       ScriptElement script = Document.get().createScriptElement();
       script.setPropertyString("language", "javascript");
       script.setPropertyString("src", "http://www.google.com/jsapi");
       Document.get().getElementsByTagName("head").getItem(0).appendChild(script);
 }

This code should be straight forward, all it's really doing is creating an HTML <script> element and setting the Google URL. Once this is added the browser fetches the JSAPI library, but the crucial thing is that it doesn't fetch the library in the boot strapper, but rather when the main UI module library has been loaded

1 comment:

Anonymous said...

Hey David,

Nice tip, please keep them coming!

If you are using the latest gwt-visualization library, it turns out that this is already being done behind the scenes in the updated AjaxLoader class:

http://code.google.com/p/gwt-google-apis/source/browse/trunk/ajaxloader/ajaxloader/src/com/google/gwt/ajaxloader/client/AjaxLoader.java

So you don't need to include jsapi.html in your host page, and it will be automatically loaded as soon as you call VisualizationUtils.loadVisualizationApi(). If you want to load the API sooner, you can invoke AjaxLoader.init() directly.