2

I'm trying to set the src attribute of a script tag using:

document.getElementById("setScript").setAttribute("src","adventures/" + setting + ".js");

The "setScript" is obviously the id of the script tag, and the setting variable is a parameter to change the script. I tested to make sure the src was actually being set, using:

alert(document.getElementById("setScript").getAttribute("src"));

Which printed out adventures/[whatever the parameter was].js. When i type exactly that in the src value in the html, it will call the function. but when it is changed in the javascript, it dos not. does anyone know why this happens?

Thanks in advance

0

2 Answers 2

2

in order to load a new javascript file you have to create a new script element with the src set and then add it to the html, eg append it to the head element

var script = document.createElement("script");
script.src = "/somescript.js";

var head = document.getElementsByName("head")[0];
head.appendChild(script);
Sign up to request clarification or add additional context in comments.

1 Comment

that makes sense, thanks i didnt think of trying that.
0

Just a shot in the dark, but I would assume that a script is only loaded when the element is added to the page.

Try something like:

var scr = document.getElementById('setScript');
scr.parentNode.removeChild(scr);
scr.src = "adventures/"+setting+".js";
document.body.appendChild(scr);

If this fails, then you will need to create a new script element, set its source, then append that.

1 Comment

that dosent seem to work either, but thanks anyways.

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.