【发布时间】:2012-01-29 08:39:49
【问题描述】:
在我的 gwt 项目中。我有一个调用字典的脚本:
<script type="text/javascript" src=conf/iw_dictionary.js></script>
而不是在 html 文件中编写此脚本元素。我想在模块加载时从入口点将其注入到 html 中。
我该怎么做?
【问题讨论】:
标签: gwt
在我的 gwt 项目中。我有一个调用字典的脚本:
<script type="text/javascript" src=conf/iw_dictionary.js></script>
而不是在 html 文件中编写此脚本元素。我想在模块加载时从入口点将其注入到 html 中。
我该怎么做?
【问题讨论】:
标签: gwt
使用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();
【讨论】:
ScriptInjector 类在 GWT_V2.7.0 中可用。如果我必须用 GWT_V.1.x 注入一个 javascript 文件,那么有可能吗?
基本上你在 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);
注入后浏览器会自动加载。
【讨论】:
您可以简单地添加<script> element in your *.gwt.xml file。
<script src='conf/iw_dictionary.js' />
onModuleLoad 只会在脚本加载后被调用(就像您在 html 页面中拥有它一样)。
【讨论】:
<script src='conf/iw_dictionary.js' /> 放入Main.gwt.xml 文件中。我的问题是,这也适用于 gwt V1.XXXX 吗?
xsiframe,它不支持模块文件中的 <script>(然后您必须使用 ScriptInjector 或包含脚本而是在您的 HTML 主机页面中)。
jusio、Dom 和 Thomas Broyer 的答案在这里都是有效的。在我的特殊情况下,我希望将一系列 polyfill 脚本注入 GWT,以获得运行原生 JS 代码时所需的一些 IE8 支持。 polyfill 脚本需要可用于 GWT iframe 的窗口上下文 - 而不是主机页面。为此,使用ScriptInjector 是正确的方法,因为它将脚本附加到该级别。您可以使用setWindow(TOP_WINDOW) 使ScriptInjector 将脚本安装到主机窗口。在我的 *.gwt.xml 文件中添加带有 <script> 标记的脚本似乎与使用 @Dom 的方法一样附加到主机窗口。
【讨论】: