How Internet Explorer conditional comments work

Conditional comments are a special feature of the Internet Explorer browser that controls the display of any HTML content based on whether the visitor is using IE or another browser, and which version of IE they are using. They are supported by Internet Explorer versions 5 to 9 inclusive; from version 10, IE no longer supports conditional comments.

I’ve seen a lot of comments on websites and forums that misunderstand how condition comments actually work, so this post is an attempt to remedy that.

The exact code can look a little complex but in reality it is quite straightforward. Conditional comments came to the fore recently with regards to the jQuery JavaScript library. The newest version 2.0 drops support for IE 8 and below in order to reduce the size of the library for modern browsers – so v1.9 should be used for IE 8 and below, with v2.0 for modern browsers.

Here is the appropriate conditional comment for loading jQuery:

<!--[if lt IE 9]>  
<script src="jquery-1.9.0.js"></script>  
<![endif]-->
<!--[if gte IE 9]><!-->
<script src="jquery-2.0.0.js"></script>
<!--<![endif]-->

Let’s walk though the code. For browsers without conditional comment support (i.e. all modern browsers), the first 3 lines of that code is one complete comment, lines 4 is one comment and line 6 is one comment. In other words, all except line 5 are ignored, therefore in modern browsers we output the script tag for jquery-2.0.0.js.

Internet Explorer, however, treats this code differently. It looks at the conditions inside the square brackets and outputs different code based on that. In the above example we have [if lt IE 9] which means “if Internet Explorer is less than version 9” – this matches IE 5-8. From that clause up to the first clause containing [endif], IE 5-8 outputs any HTML it sees – in this case the script tag for jquery-1.9.0.js.

The second section has the condition [if gte IE 9] which means “if Internet Explorer is greater than or equal to verison 9” – this matches IE 9 only, as IE 10 ignores the comment. However, the key thing to note here is that IE 5-8 now ignore line 5, even though it is not inside a comment.

In the example, lt and gte are comparison operators. The other operators are lte (less than or equal to) and gt (greater than). To match IE in general, we use [if IE]. Now that IE 10 does not support CCs, that matches IE 5-9. To match a specific version of IE we can use [if IE 6] to match version 6 and so on.

As time marches on, conditional comments will become a relic of the past. IE 9 and up are much more reliable than previous versions and stick to the standards well. We can finally write HTML and CSS that works in all browsers equally well without having to implement hacks targeting specific versions.