How to include a remote JavaScript file conditiona

2019-01-14 15:33发布

I have a HTML page.

In that, according to the browser, I need to include a separate JavaScript file.

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>

8条回答
老娘就宠你
2楼-- · 2019-01-14 16:14
<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...

查看更多
放荡不羁爱自由
3楼-- · 2019-01-14 16:19
<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.

查看更多
迷人小祖宗
4楼-- · 2019-01-14 16:26

If you're using jQuery, you could use getScript()

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

查看更多
SAY GOODBYE
5楼-- · 2019-01-14 16:29

Using conditional comments you do some HTML only in IE.

<!--[if IE]>
 <script src='iescript.js'></script>
<![endif]-->
查看更多
我命由我不由天
6楼-- · 2019-01-14 16:29

you can use conditional comments as outlined on 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:

<!--[if lt IE 7]>
<script type="text/javascript" src="/js/one.js"></script>
<![endif]-->
查看更多
闹够了就滚
7楼-- · 2019-01-14 16:31

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>");
}

查看更多
登录 后发表回答