在我的gwt项目上。我有一个调用字典的脚本:
<script type="text/javascript" src=conf/iw_dictionary.js></script>
而不是在html文件中编写此脚本元素。我想从入口点,在模块加载上将它注入到html中。
我该怎么做?
答案 0 :(得分:13)
使用com.google.gwt.core.client.ScriptInjector
,因为它是专为此类内容而创建的
ScriptInjector.fromUrl("conf/iw_dictionary.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();
答案 1 :(得分:7)
基本上你在onModuleLoad()中注入了脚本元素:
Element head = Document.get().getElementsByTagName("head").getItem(0);
ScriptElement sce = Document.get().createScriptElement();
sce.setType("text/javascript");
sce.setSrc("conf/iw_dictionary.js");
head.appendChild(sce);
浏览器会在注入后立即自动加载。
答案 2 :(得分:3)
您只需添加<script>
element in your *.gwt.xml file即可。
<script src='conf/iw_dictionary.js' />
只有在加载脚本后才会调用 onModuleLoad
(就像你在html页面中一样)。
答案 3 :(得分:0)
答案形式jusio,Dom和Thomas Broyer都在这里有效。在我的特定情况下,我希望在GWT中注入一系列polyfill脚本,以便在运行本机JS代码时获得一些IE8支持。 polyfill脚本需要可用于GWT iframe的窗口上下文 - 而不是主页。要做到这一点,使用ScriptInjector
是正确的方法,因为它在该级别附加脚本。您可以使用ScriptInjector
将setWindow(TOP_WINDOW)
脚本安装到主机窗口。在我的* .gwt.xml文件中添加带有<script>
标记的脚本似乎与使用@ Dom的方法一样附加到主机窗口。