javascripteclipse-rap

Adding and Loading Javascript to a Browser via Javascript without reloading


I have a SWT Browser in an Eclipse RAP Application, where i load something on my local server and display that html.

the url looks something like this: "http://localhost:port/......./myhtml.html"

I want to add script sources into my html without reloading the page. Currently i am doing this with a Javascript which i execute in the Browser.

var script = document.createElement('script');
script.setAttribute('src', 'SOMESOURCE');
document.head.appendChild(script);

This does work that i end up having the script tags correctly added to the HTML DOM, however it does not load the references, so i can't access anything defined in these script references. But calling something like

window.top.location.reload(false)

doesnt work either because this reloads the HTML and therefor removing my inital added script tags.

The main problem here is that i am very restricted because of the tecnologies we are using here, so i am only able to execute javascript queries in my browser.

PS: For testing you just can open any Browser like Chrome and Firefox, open its Developer Toolkit and type that script into the console. The website doesn't matter.


Solution

  • Thanks for @JensV for helping me.

    The Problem was although i added my script it didnt load its content. So what i was as described in the question.

    However as mentioned from @JensV in the Bug

    load scripts asynchronously

    it is described to use a Promise object this would handle the load and error events.

    function loadScript(src) {
        return new Promise(function (resolve, reject) {
            var s;
            s = document.createElement('script');
            s.src = src;
            s.onload = resolve;
            s.onerror = reject;
            document.head.appendChild(s);
        });
    }
    

    So what i did was first execute that Javascript and therefor adding this function, and then just execute it with the desired source.

    Thanks for @JensV again, you might wanna flag this as duplicate, however i think my problem was a bit different then that.