0

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.

Kevin Cruijssen
  • 9,153
  • 9
  • 61
  • 135
Levent Dag
  • 162
  • 8
  • 1
    This should work though... Are you waiting for the script to finish loading? Possible duplicate of: https://stackoverflow.com/a/7719185/2232127 – JensV Feb 05 '19 at 12:42
  • @JensV i did add a onload function with a alert for testing, however nothing occurs, thats why i think that the script element although it is added, it's reference is not loaded – Levent Dag Feb 05 '19 at 12:45
  • @JensV I think the Problem here is that i add the script tag after the page is loaded but i have no other option – Levent Dag Feb 05 '19 at 12:48
  • did you checked this method https://stackoverflow.com/a/19737116/4246826 – suhail c Feb 05 '19 at 12:51
  • @JensV it was not quite the same problem as in the other bug however another answer in the bug solved it for me ... using a promise object it does load the script – Levent Dag Feb 05 '19 at 12:54

1 Answers1

0

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.

Levent Dag
  • 162
  • 8