Tech Junkie Blog - Real World Tutorials, Happy Coding!: JQuery: Using Conditional Comments To Support Older Version Of Internet Explorer

Monday, April 13, 2015

JQuery: Using Conditional Comments To Support Older Version Of Internet Explorer

A lot of you may have wonder why JQuery releases versions 1.x and 2.x, the reason is because the 1.x versions are released to support older versions of Internet Explorer.   What a lot of people don't realize is that the 2.x version performs better, so if you have the choice between 1.x and 2.x you should choose the 2.x versions. Use the 1.x versions only if you have to.  In this blog we will show how to use conditional comments which Microsoft created in Internet Explorer 5.  Since it's specifically created for Internet Explorer other browsers will ignore it.   Since Internet Explorer 9 seems to be the divider for support we will use it as the base case for our conditional comments.  Here is the code to use the conditional comments to support older versions of Internet Explorer.


<html
    <head>
        <meta charset="utf-8" />
        <title>JQuery Conditional Comments Demo</title>
  <!-- [if lt IE 9]>
   <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
  <![endif]-->
  <!--[if gte IE 9]><!-->
   <script src="http://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
  <!--<![endif]-->
    </head>
    <body> 
    </body>
</html>



The code above uses the 1.x if the browser the user is using is older than Internet Explorer 9, and uses the 2.x if the Internet Explorer is greater than Internet Explorer. The important thing to note is the conditional part of the markup [if lt IE 9] says that if browser is "lt" (less than) IE 9. Load JQuery 1.x version. The same is true for the other condition [if gte IE 9] says that if the browser is "gte" (greater than or equal to) IE 9 then load the version 2.x.

Now let's add some JQuery to display the version of JQuery the browser is using, unfortunately I don't have a browser that is older than Internet Explorer 9, but a lot of your users will because of Windows XP.  So since I am using Internet Explorer 11, I should be getting the message that says I am using a 2.x version of JQuery because my browser version is gte IE 9:

<html
    <head>
        <meta charset="utf-8" />
        <title>JQuery Conditional Comments Demo</title>
  <!-- [if lt IE 9]>
   <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
  <![endif]-->
  <!--[if gte IE 9]><!-->
   <script src="http://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
  <!--<![endif]-->
  <script type="text/javascript">
   $(document).ready(function(){
    alert("JQuery Version: " + $.fn.jquery);
   });
  </script>
    </head>
    <body> 
    </body>
</html>

If you run the code above an alert message will pop-up with the JQuery version.























1 comment:

Search This Blog