简体   繁体   English

如何有条件地包含远程JavaScript文件?

[英]How to include a remote JavaScript file conditionally?

I have a HTML page. 我有一个HTML页面。

In that, according to the browser, I need to include a separate JavaScript file. 在那里,根据浏览器,我需要包含一个单独的JavaScript文件。

How is it possible? 这怎么可能?

<script type="text/javascript">
if(navigator.appName == 'Microsoft Internet Explorer')
{
//here i need to include one.js
}
else
{
//here i need to include two.js
}

</script>

最后,如果您已经在项目中使用了JQuery并且只是为它标记了标记,则可以使用$ .getScript

Here is one way, possibly not the best. 这是一种方式,可能不是最好的方式。

<script type="text/javascript">
if(navigator.appName == 'Microsoft Internet Explorer')
{
    document.write("<script tag here>");
}
else
{
    document.write("<other script tag here>");
}

Using conditional comments you do some HTML only in IE. 使用条件注释,您只在IE中执行一些HTML。

<!--[if IE]>
 <script src='iescript.js'></script>
<![endif]-->
<script type="text/javascript">
var src = navigator.appName == "Microsoft Internet Explorer" ? "one.js" : "two.js";

var script = document.createElement("script");
script.setAttribute("src", src);
document.getElementsByTagName("head")[0].appendChild(script);
</script>

Of course, you could also split the ternary operator above to your liking... 当然,您也可以根据自己的喜好将三元运算符拆分为......

If you're using jQuery, you could use getScript() 如果你正在使用jQuery,你可以使用getScript()

http://api.jquery.com/jQuery.getScript/ http://api.jquery.com/jQuery.getScript/

you can use conditional comments as outlined on http://jagregory.com/writings/using-ies-conditional-comments-for-targeted-javascript/ 您可以使用http://jagregory.com/writings/using-ies-conditional-comments-for-targeted-javascript/上列出的条件评论

for example if you wanted to target IE versions 7 and below you could: 例如,如果您想要定位IE 7及更低版本,您可以:

<!--[if lt IE 7]>
<script type="text/javascript" src="/js/one.js"></script>
<![endif]-->

I recommend you to use LAB.js or YepNope (script loaders). 我建议你使用LAB.jsYepNope (脚本加载器)。 Both make great effort on loading external scripts the best way possible. 两者都尽可能以最佳方式加载外部脚本。

For an example, using YepNope, with two conditional loads: 例如,使用YepNope,有两个条件加载:

var agent = navigator.userAgent;
yepnope({
    test : /(msie) ([\w.]+)/.test(agent), // internet explorer
    yep  : 'ie.js',
    nope : 'other-script-if-you-want.js'
});
yepnope({
    test : /(mozilla)(?:.*? rv:([\w.]+))?/.test(agent), // firefox
    yep  : 'firefox.js'
});
<script type="text/javascript">
  if(condition===true){
    document.write(unescape(
      '%3Cscript src="file1.js"%3E%3C/script%3E'+
      '%3Cscript src="file2.js"%3E%3C/script%3E'
    ));
  }
</script>

Simple and easy. 简单易行。 1 line per JS file. 每个JS文件1行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM