1

Assume that I want to use the an external JavaScript library in my GWT application. I can include myjslib.js in my module xml file with:

 <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.

Is there a way to telll GWT that myjslib.js should not be loaded if it already exist on the page?

1

1 Answer 1

3

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. Then you can inject the script using the ScriptInjector helper.

    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]

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. 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. For instance if you want to load jquery.js you can test whether $wnd.jQuery is defined.

[EDITED]

In your Javascript libary include something like:

  window.myjslib = true;

In your Java code:

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

  private native boolean isMyJsLibLoaded() /*-{
     return !!$wnd.myjslib;
  }-*/;
Sign up to request clarification or add additional context in comments.

12 Comments

I'd rather check whether some global object or method created from myjslib.js exists in the page, but otherwise yes, that's the way to go. Or rather, the way to go is to ask the user of your module to load myjslib.js in the page, and not bother loading it from the app itself (either through gwt.xml or ScriptInjector)
@ThomasBroyer Agree 100%.
@ThomasBroyer what do you mean by "Or rather, the way to go is to ask the user of your module to load myjslib.js in the page, and not bother loading it from the app itself (either through gwt.xml or ScriptInjector)" could you give an example for that?
Just have a <script src="myjslib.js"></script> in the HTML page, and nothing special in GWT, just assuming the lib has been loaded.
@ThomasBroyer how can you be sure that the lib has been loaded before the gwt tries to use it?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.