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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4609573/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 13:15:22  来源:igfitidea点击:

JavaScript IF/ELSE to call another JS Script?

javascriptif-statement

提问by Shafique

I need to call one of two JavaScripts depending on a condition, like so:

我需要根据条件调用两个 JavaScript 之一,如下所示:

<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>

But this doesnt work. Any ideas how to call another JavaScript call in an If/Else block?

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

回答by Ryan McGrath

What the hell? Why on earth is everyone here advocating document.write()? Fairly certain we've moved beyond this as standard practice by this point; document.write isn't even valid if you're in an XHTML setting.

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

The best way to do this would be something like the following (also here, for better highlighting/parsing: https://gist.github.com/767131):

最好的方法是这样的(也在这里,为了更好地突出显示/解析: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() { ... });
}

If you have jQuery or a similar library on the page, you can Hyman out my loadScript function and insert their appropriate function (ala $.getScript, etc).

如果页面上有 jQuery 或类似的库,您可以取出我的 loadScript 函数并插入相应的函数(ala $.getScript 等)。

回答by spinon

You could do something like this:

你可以这样做:

var file=document.createElement('script')
file.setAttribute("type","text/javascript")
file.setAttribute("src", "script1.js")

Forgot to add that you need to then append this into an element on the page:

忘了补充一点,您需要将其附加到页面上的元素中:

document.getElementsByTagName("head")[0].appendChild(file)

回答by Shafique

I used this and it works well:

我用过这个,效果很好:

<script type="text/javascript">
if(b_condition)
  document.write('<scri'+'pt src="http://script1.js"></'+'script>');
else
  document.write('<scri'+'pt src="http://scripts2.js"></'+'script>');
</script>

I see that document.write is not the best practice to use though, but it works. Any ideas better than this? I don't want to write so much code for something so simple.

我看到 document.write 不是使用的最佳实践,但它有效。还有比这更好的想法吗?我不想为这么简单的事情写这么多代码。

回答by pruthwiraj.kadam

   <script type="text/javascript">     
    if(condition==true)
    {
        var src = "js/testing_true.js";
        var newScript = document.createElement("script");
        newScript.type = "text/javascript";
        newScript.setAttribute("async", "true");
        newScript.setAttribute("src", src);
        document.body.appendChild(newScript);
    }else
    {

        var src = "js/testing_false.js";
        var newScript = document.createElement("script");
        newScript.type = "text/javascript";
        newScript.setAttribute("async", "true");
        newScript.setAttribute("src", src);
        document.body.appendChild(newScript);
    }
</script>

回答by Felix Kling

If the scripts are not huge and/or there is no other reason why not both should be loaded, I would do something like:

如果脚本不是很大和/或没有其他原因不应该加载两者,我会这样做:

<script type="text/javascript" src="http://script1+2.js"></script>
<script type="text/javascript">
    if(b_condition) {
        functionA();
    } 
    else {
        functionB();
    }
</script>

回答by moribvndvs

You need to either emit the desired scriptblock in your condition, or create the scripttag using the DOM and insert it. http://ajaxpatterns.org/On-Demand_Javascript

您需要script在您的条件中发出所需的块,或者script使用 DOM创建标签并插入它。http://ajaxpatterns.org/On-Demand_Javascript

回答by Arthur Neves

Those files script1.js and script2.js are your, or are u including them from another domain?

这些文件 script1.js 和 script2.js 是你的,还是你从另一个域中包含它们?

because if they are yours your can include both, and depends of your condition you can call functions inside the files..

因为如果它们是你的,你可以同时包含两者,并且取决于你的条件,你可以在文件中调用函数..

回答by Wolph

This is usually a bad idea so I recommend that you tell us what you actually need to do so we can find a better solution for you. In general you would like to combine and minify all javascript needed on the page so the user only has to load it once.

这通常是一个坏主意,因此我建议您告诉我们您实际需要做什么,以便我们为您找到更好的解决方案。通常,您希望合并和缩小页面上所需的所有 javascript,以便用户只需加载一次。

If there is no other way than you can do it like this:

如果没有其他方法,您可以这样做:

<script type="text/javascript">
    var script = document.createElement('script');
    if((b_condition){
        script.src = 'script1.js';
    }else{
        script.src = 'script1.js';
    }
    document.body.appendChild(script);
</script>

回答by Soccerwidow

<?php if (a_condition) {?>
put html code here or script or whatever you like
<?php } elseif(b_condition) {?>
put any other code here 
<?php } else {?>
put even more code
<?php } ?>

回答by alexwen

<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>