How do I load a javascript file dynamically? [duplicate]

You cannot embed HTML in Javascript in that way. Basically, what you want is to embed a script element, pointing to a certain javascript file when clicking a button. That can be done with combining events with DOM:

<script type="application/javascript">
function loadJS(file) {
    // DOM: Create the script element
    var jsElm = document.createElement("script");
    // set the type attribute
    jsElm.type = "application/javascript";
    // make the script element load file
    jsElm.src = file;
    // finally insert the element to the body element in order to load the script
    document.body.appendChild(jsElm);
}
</script>
<button onclick="loadJS("https://stackoverflow.com/questions/5235321/file1.js");">Load file1.js</button>
<button onclick="loadJS('file2.js');">Load file2.js</button>

Leave a Comment