setting src of html <script> in javascript

江枫思渺然 提交于 2019-12-24 04:06:08

问题


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


回答1:


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



回答2:


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.



来源:https://stackoverflow.com/questions/21371737/setting-src-of-html-script-in-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!