Eric
Eric

Reputation: 1444

GWT: Can I include js in html page or do I need `ScriptInjector`?

I am adding an html file to my GWT page like so:

HTML htmlPanel = new HTML();
String html = MyHtml.INSTANCE.getHtml().getText();
htmlPanel.setHTML(html);
RootPanel.get().add(htmlPanel);

and that works ... but the embedded script files don't run. I see the line in Chrome's Elements tab where the script should be loaded, but apparently it is not (doesn't show up in the Scripts tab, and debugger lines are not hit).

As a test, I loaded the html file straight into my browser (not via GWT), and the script does show up in the Scripts tab and it does run the code (so it's not an issue with the script tag itself).

So ... why/how do the scripts not run when embedded by GWT? (I wouldn't know how to keep an embedded script from running if I tried!) ;o)

Do I have to use the ScriptInjector to make this work (I'm having my own problems with getting that working, which is a subject for another thread)? If so ... why?

Thanks for your help!

Upvotes: 0

Views: 698

Answers (1)

Colin Alworth
Colin Alworth

Reputation: 18331

Creating the script by adding it to an HTML widget and appending it to the page will not work, this is not supported by the browser. GWT isn't doing this, the browser is, or rather, the browser is doing it because of how the HTML widget works. For specifics on why this is the case, see the great answer at https://stackoverflow.com/a/13392818/860630 that digs into the details.

There are several other ways you can do this, but they all boil down to the work that the ScriptInjector is already doing - if ScriptInjector doesn't work for you, it seems unlikely that the other options will behave either. Maybe edit your question to use ScriptInjector and describe your issues, or ask a new question with it? The only cases where I've seen ScriptInjector not work is related to $wnd, or which page the script is appended to (see com.google.gwt.core.client.ScriptInjector#TOP_WINDOW).

Upvotes: 1

Related Questions