Question

I have some external Javascript files in my GWT app that I only want to download when the user accesses the section that requires them. I included the JS files in a UiBinder page like so:

<g:HTMLPanel>
    <script src="blah.js"/>
</g:HTMLPanel>

The files won't necessarily be downloaded as soon as the view is loaded, so when I load the view, I check for an exception indicating that the external code isn't accessible and try again until the view can be created without an exception.

This works in Firefox but it doesn't work in IE7/IE8. I used AJAX Edition to trace what's happening in IE, and a request for the file is made but it doesn't download anything, the size is 0. The web server access logs don't show that the file was requested.

Any idea what's going on?

Or is there a better way to do this? The investigating I've done thus far does not indicate that GWT has a convenient way to do this.

Update:

Although we're not on 2.4 yet, just to try I copied in the source files needed for ScriptInjector and attempted to use that per the suggestion by Thomas. The JS files download correctly in both browsers, but I get the '$wnd.xxxx is undefined' exception indicating that the references in the external script can't be found. I don't try to load my widget until the onSuccess() call returns from the script inject - so my code looks something like this:

ScriptInjector.fromUrl("../xxxx.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."); 
           MyWidget widget = new MyWidget(); 
           client.onSuccess(widget); // adds the widget to the view 
         } 
      }).inject(); 

I also don't see the JS file references added to the DOM in Firebug, but I wonder if that is because they are being added to the DOM of the GWT portion of the page, not to the actual index.jsp.

Était-ce utile?

La solution

you need to tell the ScriptInjector to add the script to the top level window.

ScriptInjector.fromUrl(scriptUrl)
    .setWindow(ScriptInjector.TOP_WINDOW)
    .setCallback(new Callback<Void, Exception>() {
        @Override
        public void onSuccess(Void result) {
            //script loaded OK
        }

        @Override
        public void onFailure(Exception reason) {
            //TODO script injection failed
        }
    }).inject();

Autres conseils

Script elements inserted using innerHTML (which is what HTMLPanel uses) are not executed.

You'll have to use ScriptInjector to dynamically inject a script into your page.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top