Oct 7, 2009

Conditional comments parsing

What are conditional comments?

Conditional comments allow you to hide (or show) a part of HTML code for IE-based / not IE browsers. You can find compelete guide about this technique here or in MSDN. Small example:

<!--[if IE 8]>
<p>Welcome to Internet Explorer 8.</p>
<![endif]-->

In all browsers (except IE8) we don't see anything for this code, it behaves itself as a standard HTML comment. IE8 will parse this chunk as a paragraph with text. There is one more wonderful technique from Microsoft - conditional complilation inside JavaScript - but it's out of scope of this article.

Why such comments are evil?

Usually webmasters create templates of the website for all browsers except IE, and then add IE-specific styles with conditional comments. They include separate files to improve these styles caching. It's great. But IE7- uses only 1 connection to load JS files (2 for CSS, but this doesn't change a lot), so it's additional HTTP request(s) and additional payload (in case of 1 merged global CSS file and 2 files in conditional comments there also will be some time wasted). We can prevent this.

Show me the magic!

We can detect browser on the server (by User Agent string) and just strip out conditional comments if they match current browser (IE). So comments that must work in IE are just uncommented in the document head, and latter is parsed in a common order.

All this leads to difference between "general" version of cached files and "IE" ones. So we just need to separate cached files by browser - for each browser receives its own cache file (right now 4 for IE and 1 for others), and all will be OK.

All this has been included into Web Optimizer and will be available in version 0.6.2.

2 comments:

  1. The only thing mising is:

    Which options are affected & what to do for which effect.
    And how to test it :)

    ReplyDelete
  2. Markus, it's general approach of underlying logic. Like parsing head or body tag. So if we are working with head -- the whole head will be parsed for conditional comments. If we are working with body - the whole body.

    You can just place any conditional comments in head and play with them to see the result.

    ReplyDelete