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

有帮助吗?

解决方案

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);

其他提示

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.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top