如何动态加载javascript文件?

use*_*318 27 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>
Run Code Online (Sandbox Code Playgroud)

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

我怎样才能做到这一点?

Lek*_*eyn 60

你不能以这种方式在Javascript中嵌入HTML.基本上,你想要的是嵌入一个脚本元素,在单击按钮时指向某个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>
Run Code Online (Sandbox Code Playgroud)

  • 请注意,在调用"document.body.appendChild(jsElm);"之后,加载的javascript文件中的函数不可用,但是有jsElem.onload事件在js准备就绪时发出信号. (6认同)

Jim*_*ket 9

试试这个尺寸:动态加载JS

function loadjscssfile(filename){
  var fileref=document.createElement('script')
  fileref.setAttribute("type","text/javascript")
  fileref.setAttribute("src", filename)
 if (typeof fileref!="undefined")
  document.getElementsByTagName("head")[0].appendChild(fileref)
}

loadjscssfile("myscript.js") //dynamically load and add this .js file
Run Code Online (Sandbox Code Playgroud)


gil*_*ly3 5

JavaScript的:

function loadScript(url)
{
    document.body.appendChild(document.createElement("script")).src = url;
}
function loadDefaultScript()
{
    loadScript("http://mysite.com/file1.js");
}
function loadAlternateScript()
{
    loadScript("http://mysite.com/file2.js");
}
Run Code Online (Sandbox Code Playgroud)

HTML:

<input type="button" onclick="loadAlternateScript()" value="Alternate" />
<input type="button" onclick="loadDefaultScript()" value="Default" />
Run Code Online (Sandbox Code Playgroud)

  • 服务器是mime类型的权威来源.type属性始终被忽略,而不仅仅是HTML5.包含它没有任何好处.这实际上是一个缺点,因为它具有误导性. (5认同)
  • `type`属性在HTML5中是可选的. (2认同)