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>
And finally, if you're already using JQuery in your project and just left out the tag for it, you can use $.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.
<!--[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()
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/
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]-->
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'
});
<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.