How to include a remote JavaScript file conditionally?

37,911

Solution 1

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

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

Solution 3

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

Solution 4

Using conditional comments you do some HTML only in IE.

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

Solution 5

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

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

Share:
37,911
Linto
Author by

Linto

Updated on July 24, 2022

Comments

  • Linto
    Linto almost 2 years

    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>