简体   繁体   English

当包含在gwt.xml中时如何跳过加载外部JavaScript库?

[英]How skip loading external JavaScript library from being loaded when included in gwt.xml?

Assume that I want to use the an external JavaScript library in my GWT application. 假设我想在GWT应用程序中使用外部JavaScript库。 I can include myjslib.js in my module xml file with: 我可以在我的模块xml文件中包含myjslib.js:

 <script src="myjslib.js"></script>

Here is the problem: If the my GWT app is not a full page application, than it could be possible that the html page that contains my GWT app has allready loaded the myjslib.js file. 问题在于:如果我的GWT应用程序不是整页应用程序,那么包含我的GWT应用程序的html页面可能已经加载了myjslib.js文件。

Is there a way to telll GWT that myjslib.js should not be loaded if it already exist on the page? 有没有办法telll GWT myjslib.js如果它已经存在于页面上那么不应该加载?

There is no way using the .gwt.xml file, you can though, do it in your code visiting all '<script>' tags of your document and checking whether the src attribute matches your library name. 无法使用.gwt.xml文件,您可以在代码中访问文档的所有“<script>”标记并检查src属性是否与您的库名称匹配。 Then you can inject the script using the ScriptInjector helper. 然后,您可以使用ScriptInjector帮助程序注入脚本。

    NodeList<Element> scripts = Document.get().getElementsByTagName("script");
    for (int i = 0; i < scripts.getLength(); i++) {
      Element e = scripts.getItem(i);
      if (e.getAttribute("src").matches(".*myjslib.js")) {
        return;
      }
    }
    ScriptInjector.fromUrl("myjslib.js").inject();

[EDITED] [EDITED]

As @ThomasBroyer says in his first comment, the easiest way to load the script is adding a <script> tag in the head of your page. 正如@ThomasBroyer在他的第一条评论中所说,加载脚本的最简单方法是在页面的头部添加<script>标记。 And the most reliable way to be sure that the script has been loaded before using it in GWT is knowing that some property has been set in the window object. 在GWT中使用脚本之前确保脚本已加载的最可靠方法是知道在窗口对象中设置了一些属性。 For instance if you want to load jquery.js you can test whether $wnd.jQuery is defined. 例如,如果要加载jquery.js,可以测试是否定义了$ wnd.jQuery。

[EDITED] [EDITED]

In your Javascript libary include something like: 在您的Javascript库中包括以下内容:

  window.myjslib = true;

In your Java code: 在您的Java代码中:

  public void OnModuleLoad() {
     if (isMyJsLibLoaded() == false) {
        ScriptInjector.fromUrl("myjslib.js").inject();
     }
  }

  private native boolean isMyJsLibLoaded() /*-{
     return !!$wnd.myjslib;
  }-*/;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM