How to make your Javascript work conditionally, depending on the browser?

I want to run Javascript if the browser is not IE, or IE 9+. If the browser is IE8 or lower, another Javascript should work.

I tried using Conditional Comments :

<!--[if (!IE)|(gte IE 9)]>
    <script type="text/javascript"> /* code 1 */ </script>
<![endif]-->

<!--[if (lt IE 9)]>
    <script type="text/javascript"> /* code 2 */ </script>
<![endif]-->

But IE6 and IE7 were still running code 1 . And Firefox was executing code 2 ...

No jQuery, please.

Edit: Actually my conditional expression was wrong. But still I went with the feature discovery suggested in the selected answer.

+5
source share
3 answers

, , , document.getElementsByClassName(). :

if (document.getElementsByClassName) {
    // code here that uses getElementsByClassName
} else {
    // code here that doesn't use getElementsByClassName
}

polyfill, IE . Google. :

// Add a getElementsByClassName function if the browser doesn't have one
// Limitation: only works with one class name
// Copyright: Eike Send http://eike.se/nd
// License: MIT License

if (!document.getElementsByClassName) {
  document.getElementsByClassName = function(search) {
    var d = document, elements, pattern, i, results = [];
    if (d.querySelectorAll) { // IE8
      return d.querySelectorAll("." + search);
    }
    if (d.evaluate) { // IE6, IE7
      pattern = ".//*[contains(concat(' ', @class, ' '), ' " + search + " ')]";
      elements = d.evaluate(pattern, d, null, 0, null);
      while ((i = elements.iterateNext())) {
        results.push(i);
      }
    } else {
      elements = d.getElementsByTagName("*");
      pattern = new RegExp("(^|\\s)" + search + "(\\s|$)");
      for (i = 0; i < elements.length; i++) {
        if ( pattern.test(elements[i].className) ) {
          results.push(elements[i]);
        }
      }
    }
    return results;
  }
}
+5

javascript HTML. JS navigator.userAgent, ( IE ). JS- - , :

if(navigator.userAgent.indexOf('MSIE 9.0') !== -1)
{
  // call IE9 specific method
}
else
{
  // call method for other browsers
}

. navigator.userAgent

0

Since defining a jfriend00 function might be the best solution, but here are conditional comments that suit your requirements.

<!--[if gte IE 9]> -->
    <script type="text/javascript"> alert('ie9+ and not ie') </script>
<!-- <![endif]-->
<!--[if lt IE 9]>
    <script type="text/javascript"> alert(' < ie9') </script>
<![endif]-->

http://jsfiddle.net/szF4J/1/

0
source

All Articles