1

I'm working on maintenance project which was developed with GWT version 1.x. Now I have to add some extra features in the same project and for that I have to inject external JavaScript file into GWT application. So I have done a bit of research to achieve the same and I can understand that I can inject the external JavaScript with the help of ScriptInjector class [Source]. but this class is available in GWT version GWT 2.7.0 and I'm using the older version of GWT.

So I would like to know that Can I inject the external JavaScript file without ScriptInjectorclass?

Community
  • 1
  • 1
SK.
  • 4,174
  • 4
  • 30
  • 48

2 Answers2

0

Maybe you can copy the sources of ScriptInjector into your project: https://gwt.googlesource.com/gwt/+/master/user/src/com/google/gwt/core/client/ScriptInjector.java

Philippe Gonday
  • 1,747
  • 5
  • 21
  • 32
  • I haven't done this before so How can I copy the sources of `ScriptInjector` class into my project. Where I have to put it. – SK. Dec 15 '14 at 13:17
0
public class JavaScriptInjector {

    private static ScriptElement createScriptElement() {
        ScriptElement script = Document.get().createScriptElement();
        script.setAttribute("type", "text/javascript");
        script.setAttribute("charset", "UTF-8");
        return script;
    }

    protected static HeadElement getHead() {
        Element element = Document.get().getElementsByTagName("head")
                .getItem(0);
        assert element != null : "HTML Head element required";
        return  HeadElement.as(element);
    }


     /**
     * Injects the JavaScript code into a
     * {@code <script type="text/javascript">...</script>} element in the
     * document header.
     *
     * @param javascript
     *            the JavaScript code
     */
    public static void inject(String javascript) {
        HeadElement head = getHead();
        ScriptElement element = createScriptElement();
        element.setText(javascript);
        head.appendChild(element);
    }
}

This works if you have your JavaScript as a TextResource. If you want to load from a URL, you can specify the element.setSrc(yourURL) instead of element.setText(javascript). You can also load the javascript from the URL as a HTTP GET and do the setText anyway.

André
  • 2,184
  • 1
  • 22
  • 30