JavaScript IF/ELSE调用另一个JS脚本?

Sha*_*que 8 javascript if-statement

我需要根据条件调用两个JavaScripts中的一个,如下所示:

<script type="text/javascript">
if(b_condition)
  <script type="text/javascript" src="http://script1.js"></script>
else
  <script type="text/javascript" src="http://script2.js"></script>
</script>
Run Code Online (Sandbox Code Playgroud)

但这不起作用.有关如何在If/Else块中调用另一个JavaScript调用的任何想法?

Rya*_*ath 15

我勒个去?为什么这里的每个人都崇尚document.write()?相当肯定我们已经超越了这一点作为标准做法到此为止; 如果您处于XHTML设置中,document.write甚至无效.

执行此操作的最佳方法如下所示(此处为了更好地突出显示/解析:https://gist.github.com/767131):

/*  Since script loading is dynamic/async, we take
    a callback function with our loadScript call
    that executes once the script is done downloading/parsing
    on the page.
*/
var loadScript = function(src, callbackfn) {
    var newScript = document.createElement("script");
    newScript.type = "text/javascript";
    newScript.setAttribute("async", "true");
    newScript.setAttribute("src", src);

    if(newScript.readyState) {
        newScript.onreadystatechange = function() {
            if(/loaded|complete/.test(newScript.readyState)) callbackfn();
        }
    } else {
        newScript.addEventListener("load", callbackfn, false);
    }

    document.documentElement.firstChild.appendChild(newScript);
}

if(a) {
    loadScript("lulz.js", function() { ... });
} else {
    loadScript("other_lulz.js", function() { ... });
}
Run Code Online (Sandbox Code Playgroud)

如果你在页面上有jQuery或类似的库,你可以插入我的loadScript函数并插入它们适当的函数(ala $ .getScript等).


ale*_*wen -2

<script type="text/javascript">
   if(b_condition)
      document.write('<script type="text/javascript" src="http://script1.js"></script>');
   else
      document.write('<script type="text/javascript" src="http://script2.js"></script>');
</script>
Run Code Online (Sandbox Code Playgroud)