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>
Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
Linto
  • 1,234
  • 3
  • 25
  • 41
  • 2
    possible duplicate of [Include JavaScript file inside JavaScript file?](http://stackoverflow.com/questions/950087/include-javascript-file-inside-javascript-file) – Lightness Races in Orbit Nov 10 '11 at 19:26

8 Answers8

18

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

BNL
  • 7,085
  • 4
  • 27
  • 32
  • 3
    I like this way the best because it fits right in-line with the other ` – pejalo Mar 31 '17 at 20:05
18

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

Dave
  • 4,375
  • 3
  • 24
  • 30
11
<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...

hi im zvaehn
  • 91
  • 1
  • 10
Demian Brecht
  • 21,135
  • 5
  • 42
  • 46
7

Using conditional comments you do some HTML only in IE.

<!--[if IE]>
 <script src='iescript.js'></script>
<![endif]-->
TJHeuvel
  • 12,403
  • 4
  • 37
  • 46
2

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

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

Mike Christensen
  • 88,082
  • 50
  • 208
  • 326
0
<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.

Slava
  • 2,887
  • 3
  • 30
  • 39
0

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]-->
Ryan
  • 109
  • 6
0

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