如何将GWT应用程序集成到另一个Web框架中?

时间:2010-04-08 10:43:59

标签: javascript gwt echo2

我需要能够在Echo2环境中随时加载和启动GWT应用程序。我的第一种方法是使用

在客户端 - 服务器同步中加载和执行nocache.js
var script = document.createElement("script");
script.setAttribute("src",javascriptURI);
script.setAttribute("type","text/javascript");
document.getElementsByTagName('body')[0].appendChild(script);

此调用基本上有效,但是当脚本执行时,它会在EMPTY文档上运行,而不是在Echo2应用程序的当前文档上运行。脚本是以某种方式首先初始化还是需要任何事件?

如果GWT应用程序/脚本包含在应用程序的启动HTML中,则它可以正常工作,因此我认为GWT应用程序是正确的。 GWT应用程序的原始独立HTML也在正文中包含HTML脚本标记。

1 个答案:

答案 0 :(得分:1)

问题是,nocache.js文件中的dowcument.write调用仅在文档尚未完成加载时才有效。否则document.write将覆盖整个文档。

因此,document.write调用必须由DOM的createElement方法替换:

对于添加带有标记ID的脚本的第一个代码:

var script = document.createElement("script");
script.setAttribute("id", markerId);
$doc_0.getElementsByTagName("body")[0].appendChild(script);

对于第二部分(几乎在nocache.js的末尾)。将“app”替换为您的应用程序名称:

try {
    var script = document.createElement("script");
    script.setAttribute("defer", "defer");
    script.innerHTML = "app.onInjectionDone('app')";
    $doc_0.getElementsByTagName("body")[0].appendChild(script);
} catch (e) {
    // Fallback if we want to use the original html page without embedding in IE
    $doc_0.write('<script defer="defer">app.onInjectionDone(\'app\')<\/script>');
}

因此,这是必须在gwt生成的代码中修补的部分。 现在是用户单击按钮时加载和启动应用程序的html页面:

<html> 
  <head> 
    <!-- base url --> 
    <base href="http://localhost:8080/app/" /> 
    <meta http-equiv="content-type" content="text/html; charset=UTF-8"> 
    <link type="text/css" rel="stylesheet" href="static-gwt.css"> 
    <title>APP</title> 
    <script type="text/javascript"> 

    function startApp() {
        if (document.createElement && document.getElementsByTagName) {
          var script = document.createElement('script');
          script.type = 'text/javascript';
          script.src = 'app/app.nocache.js';
          var heads =document.getElementsByTagName('body');
          if (heads && heads[0]) {
            heads[0].appendChild(script);
            triggerAppStart();
          }
        }
    }

    function triggerAppStart(){
        try{
        app.onInjectionDone('app');
        if ( !document.createEventObject ) {
            var evt = document.createEvent("HTMLEvents");
            evt.initEvent("DOMContentLoaded", true, true);
            document.dispatchEvent(evt);
           }
        } catch ( e ) {
        window.setTimeout('triggerAppStart()', 100 );
       } 
    }

</script> 
  </head> 
  <body> 
    <input type="button" onclick="startApp();return false;"> 
  </body> 
 </html> 

我知道这不是最好的解决方案,但它是迄今为止唯一有效的方法。