How to include a remote JavaScript file conditiona

2019-01-14 16:26发布

问题:

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>

回答1:

And finally, if you're already using JQuery in your project and just left out the tag for it, you can use $.getScript



回答2:

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



回答3:

Using conditional comments you do some HTML only in IE.

<!--[if IE]>
 <script src='iescript.js'></script>
<![endif]-->


回答4:

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



回答5:

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

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



回答6:

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:

I recommend you to use LAB.js or YepNope (script loaders). Both make great effort on loading external scripts the best way possible.

For an example, using YepNope, with two conditional loads:

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


回答8:

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