簡體   English   中英

如何有條件地包含遠程JavaScript文件?

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

我有一個HTML頁面。

在那里,根據瀏覽器,我需要包含一個單獨的JavaScript文件。

這怎么可能?

<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

這是一種方式,可能不是最好的方式。

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

使用條件注釋,您只在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>

當然,您也可以根據自己的喜好將三元運算符拆分為......

如果你正在使用jQuery,你可以使用getScript()

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

您可以使用http://jagregory.com/writings/using-ies-conditional-comments-for-targeted-javascript/上列出的條件評論

例如,如果您想要定位IE 7及更低版本,您可以:

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

我建議你使用LAB.jsYepNope (腳本加載器)。 兩者都盡可能以最佳方式加載外部腳本。

例如,使用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>

簡單易行。 每個JS文件1行。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM