一尘不染

如何动态加载JavaScript文件?

javascript

我有以下代码:

    <script type="text/javascript">
    function js() {
        var getJs = document.getElementById("jogo");

        if (JS == true) { //if button JS is pressed - it is correct?

            < script type = "text/javascript"
            src = "file1.js" >


        } else < script type = "text/javascript"
        src = "file2.js" >
</script>
}
</script>

它不起作用。我给了两个按钮,如果按下第一个,则file1.js应该加载。如果第二个被按下,file2.js则应加载。

我怎样才能做到这一点?


阅读 230

收藏
2020-05-01

共1个答案

一尘不染

您不能以这种方式将HTML嵌入Javascript。基本上,您想要的是嵌入一个脚本元素,单击按钮时指向某个javascript文件。可以通过将事件与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('file1.js');">Load file1.js</button>
<button onclick="loadJS('file2.js');">Load file2.js</button>
2020-05-01