从JS代码中包含JS文件的最佳方法是什么?

Sha*_*eem 8 javascript

从另一个Javascript文件中包含Javascript文件的推荐方法是什么?

Rya*_*rty 5

大多数人将JavaScript文件添加到文档的头部:

<script type="text/javascript">
  var newfile=document.createElement('script');
  newfile.setAttribute("type","text/javascript");
  newfile.setAttribute("src", '/myscript.js');
  document.getElementsByTagName("head")[0].appendChild(newfile);
</script>
Run Code Online (Sandbox Code Playgroud)


Ben*_*Ben 0

这个怎么样:

原链接

<script type="text/javascript">
// Function to allow one JavaScript file to be included by another.
// Copyright (C) 2006-08 www.cryer.co.uk
function IncludeJavaScript(jsFile)
{
  document.write('<script type="text/javascript" src="'
    + jsFile + '"></scr' + 'ipt>'); 
}
</script>
Run Code Online (Sandbox Code Playgroud)

然后要包含第二个 JavaScript 文件,只需添加以下行:

IncludeJavaScript('secondJS.js');
Run Code Online (Sandbox Code Playgroud)

来自的页面包含此方法产生的一些问题,因此在使用该方法之前值得查看。