GWT - Inject external JavaScript file into GWT application without ScriptInjector

1.2k Views Asked by At

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?

2

There are 2 best solutions below

1
On

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

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