Internet Explorer’s conditional comments can be useful for applying different style sheets to older versions of Internet Explorer without having to hack your style sheets up too much. There are several different ways to target versions of Internet Explorer with condition comments by making the code between the conditions look like a regular HTML comment to other browsers. It is also possible to target particular versions of IE and also let all other browsers access the code between the comments. This post looks at how to do this, using a Javascript include file as an example.
If you wanted to include a Javascript library, like jQuery for example, for only Internet Explorer 6.0 and higher, and also all other browsers, you could do something like this:
<!--[if gte IE 6]> <script language="javascript" type="text/javascript" src="/js/jquery-1.2.3.js"></script> <![endif]--> <![if !IE]> <script language="javascript" type="text/javascript" src="/js/jquery-1.2.3.js"></script> <![endif]>
The first condition says that for Internet Explorer 6 and higher use the code between the tags and include the Javascript file; older versions will ignore the code and not include the file. The second condition says all non Internet Explorer browsers should use this code and include the file.
The only problem with the above example is you end up having to put the same <script> tag in twice and use up more space than is necessary. Fortunately it’s possible to combine the two into a single conditional comment like so:
<!--[if gte IE 6]><!--> <script language="javascript" type="text/javascript" src="/js/jquery-1.2.3.js"></script> <!--<![endif]-->
The same code example again, but this time with emphasis so you can see the additional parts added to the first conditional comment in the first example:
<!--[if gte IE 6]><!--> <script language="javascript" type="text/javascript" src="/js/jquery-1.2.3.js"></script> <!--<![endif]-->
This works the same way as the first example above but is more concise and only requires the <script> tag to be in the HTML code once.