javascript 如何有条件地包含外部javascript文件?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26979733/
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-10-28 06:46:36  来源:igfitidea点击:

How to include an external javascript file conditionally?

javascriptinclude

提问by mukto90

I have this code:

我有这个代码:

<script src="http://external/js/file/url.js">
</script>

I want to do something like this-

我想做这样的事情-

<script>
if(2>1){
//include http://external/js/file/url.js
}
</script>

Any idea?

任何的想法?

回答by Callum

This question has been asked before in Include a Javascript File in another Javascript File. This peice of code may fit what you have been looking for

之前在Include a Javascript File in another Javascript File 中已经问过这个问题。这段代码可能适合您一直在寻找的内容

function include(filename)
{
   var head = document.getElementsByTagName('head')[0];

   var script = document.createElement('script');
   script.src = filename;
   script.type = 'text/javascript';

   head.appendChild(script)
}   

if that script does not work, i suggest you to look over and read the post above: Include a Javascript File in another Javascript File.

如果该脚本不起作用,我建议您查看并阅读上面的帖子:Include a Javascript File in another Javascript File

I hope this helps, it may not be the answer you had been looking for, but it may just help.

我希望这会有所帮助,它可能不是您一直在寻找的答案,但它可能只是有所帮助。

回答by ????? ?????

You simply load it asynchronously like

你只需像异步加载它

if(yourCondition==true){
var d = document,
            h = d.getElementsByTagName('head')[0],
            s = d.createElement('script');
    s.type = 'text/javascript';
    s.async = true;
    s.src = 'http://external/js/file/url.js';
    h.appendChild(s);
}

回答by ajtrichards

You could use something like:

你可以使用类似的东西:

<script type="text/javascript">

   if (condition == true) {

      document.getElementsByTagName("head")[0].innerHTML += ("<script src=\"http://external/js/file/url.js\" type=\"text/javascript\"></script>");

   }

</script>