Cannot change html script src with external javascript

- 1 answer

Ad

I have read every single google result I could find, and this still is not working... all i'm trying to do is change a script source depending on a link that is clicked. The source files will have one or two lines returned by document.write, like so:

document.write(`This is content script a`);

So I have the following setup, an html file with two links that call the changeSrc function, which SHOULD change the source:

<!DOCTYPE html>
<html>
	<body>
		<a id="aLink" target="_blank" rel="nofollow noreferrer" target="_blank" rel="nofollow noreferrer" href="#" onclick="changeSrc('a');return false;">Change to a</a/><br>
		<a id="aLink" target="_blank" rel="nofollow noreferrer" target="_blank" rel="nofollow noreferrer" href="#" onclick="changeSrc('b');return false;">Change to b</a/><br>
		<script id="contentScript" src="a.js"></script>
	</body>
</html>

The JS file:

function changeSrc (arg) {
    document.getElementById("contentScript").innerHTML = '';
    if (arg == "a") {
        document.getElementById("contentScript").innerHTML = '<script id="contentScript" src="a.js"></script>';
    } else if (arg == "b") { {
        document.getElementById("contentScript").innerHTML = '<script id="contentScript" src="b.js"></script>';
    }

}

Why is the script source not changing on the link click?!

Thank you for your time, I feel like an absolute idiot...

Ad

Answer

Ad

Try

document.getElementById("ContentScript").src = your_script_source_here

Hope this helps!

Ad
source: stackoverflow.com
Ad