11

I have a widget depending on some external JS files, and I'd like to lazy load all these external resources. I've already used code splitting to lazy load the GWT code that concerns the widget, but the JS files defined in the gwt.xml, using the script tag, are loaded anyway, which is not desirable.

Is there a standard GWT way of loading these external resources on demand? I can do it myself using raw JS, but I'd rather not spend time on this too.

Ionuț G. Stan
  • 176,118
  • 18
  • 189
  • 202
  • There's even more discussion of this over on the GWT Google group: ["How to include 3rd party Javascript libraries in a reusable gwt library/widget?"](https://groups.google.com/d/topic/google-web-toolkit/Xiz8XmPhJzo/discussion) – blong Apr 09 '13 at 14:13

2 Answers2

18

I think you'll want to take a look at the com.google.gwt.core.client.ScriptInjector class. From the javadocs:

Dynamically create a script tag and attach it to the DOM.

...

Usage with script loaded as URL:

   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();

This code can of course be invoked from within your split points, or indeed anywhere in your code.

Colin Alworth
  • 17,801
  • 2
  • 26
  • 39
  • Brilliant! Thanks Colin. Although, now I'll have to migrate from 2.3 to 2.4 :) I'll see how it goes. – Ionuț G. Stan Nov 01 '11 at 21:05
  • 1
    2.3 to 2.4 shouldn't be a big deal, but if it is, you can look at how ScriptInjector.fromUrl works with the ScriptElement, and you can build it into your app without upgrading. – Colin Alworth Nov 02 '11 at 01:43
1

ScriptInjector is quite portable. It doesn't have any external dependencies, so you should be able to backport it into your 2.3 application without much problem.

barni
  • 56
  • 2