Conditional comments block downloads

May 23rd, 2010. Tagged: CSS, performance

I came across this blog post (via @pornelski and @souders) where Markus has stumbled upon a case where an IE6-only stylesheet included with a conditional comment blocks the downloads in IE8. Whaaat?

I had to dig in. To give you a summary: turned out that any conditional comment, not only for an extra CSS, will block further downloads until the main CSS file arrives. Also the solution offered on the blog post (using X-UA-Compatible) seems to be more of an error due to an accidentally left comment.

Check out the tests.

Base page

The first test is the base page. It follows a pretty common style pattern - CSS at the top, a bunch of images in the middle, JS at the bottom.

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN"
    <title>The base page</title>
    <link type="text/css" rel="stylesheet" 
    <img src="" alt="1">
    <img src="" alt="2">
    <img src="" alt="3">
    <img src="" alt="4">
<script type="text/javascript" 

The waterfall produced by WebPageTest looks like so:

base page

The page is here, the results of the WebPageTest's test are here.

Conditional IE6 stylesheet

Adding a second stylsheet to the head like so:

  <title>base page</title>
  <link type="text/css" rel="stylesheet" 
  <!--[if IE 6 ]>    
    <link type="text/css" rel="stylesheet" 

Turns out that this conditional comment blocks further downloads until the main CSS arrives.

Test page, test results, waterfall:

CC style page

Just like that the total page to onload time went up from 1 second to almost 1.3 seconds. Ouch.

And this is because of an IE6 stylesheet, which IE8 has no use for. My wild guess is that IE needs to parse through those conditional comments and treats them sort of like inline script. And we know that inline scripts following a stylesheet tend to block.

Conditional markup

What if we don't include IE6 specific stylsheet, but use the conditional comments to write different body tags with different class names, as described by Paul Irish.

<!--[if IE 6]> <body class="ie6"> <![endif]--> 
<!--[if !IE]><!--> <body> <!--<![endif]-->

Turns out that these markup conditional comments will also block downloads until the CSS arrives.

Test page, test results, waterfall looks as bad (the same blocking).

Browser-sniffing comments

I blogged about this a few days ago - using conditional comments to do the browser sniffing and include appropriate CSS - one for normal browsers and a complete alternative for IE6,7.

  <!--[if lte IE 7]>
    <link type="text/css" rel="stylesheet" 
  <!--[if gt IE 7]><!-->
    <link type="text/css" rel="stylesheet" 

Turns out this is OK to do. The conditional comments are processed before the download is initiated, so there't nothing to block on after the stylesheet. Yeey!

Test page, test results, waterfall looks like the first one for the base page.

X-UA-Compatible not a solution

The blog post suggested using the X-UA-Compatible meta tag to say that the UA is the latest IE possible.

<meta http-equiv="X-UA-Compatible" content="IE=edge">

It didn't work for me.

Test page, test results, waterfall like the second (the blocking) one.

Looking closely and thanks to the screenshots digging out the original test page I noticed that it contains a dangling comment. Putting that dangling comment in a test page, and the blocking effect was gone. But this is a bug. In fact the comment shows up on the page! My wild guess is that this improper comments invalidates the following one and that's why there's no blocking. I guess that IE6 will not load the stylesheet, but I didn't test.

So my tests - with X-UA meta tag (results) and with comment bug (results)

Conclusions, conclusions

To summarize, if you worry about performance, don't use conditional comments.

There might be an exception when you put a script in the head after the CSS - then there are two blocking things, so the effect of the conditional comment is not visible. But that's still bad for performance, there's still blocking.

It's OK to use the browsers-sniffing comments approach, provided of course, that there's no other CSS file before the sniff. If there is one, it will block.

Best - just use _ and * hacks, go with a single CSS and forget sniffing.

Update: empty conditional comment

Thanks to Markus who kept looking into the extra conditional comment comes a solution: an empty conditional comment early on solves the blocking issue.. By "early on" I mean before the main CSS which caused the blocking.

I did two more tests to validate the solution and it absolutely works.

One test has empty comment + conditional comment for writing Paul's body tags. The empty comment (aka the solution) is right before the blocking CSS file.

    <title>base page</title>
    <!--[if IE 6]><![endif]-->
    <link type="text/css" rel="stylesheet" 
<!--[if IE 6]> <body class="ie6"> <![endif]-->
<!--[if !IE]><!--> <body> <!--<![endif]-->

Test page, webpagetest results. Works as advertised, no more blocking.

The second test uses empty comment and conditional stylesheet. In this case I even put the empty comment way at the top. Sort of like declaring upfront - hey this page uses conditional comments and the empty comment is the solution to the blocking effect.

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN"
<!--[if IE 6]><![endif]-->
  <title>base page</title>
  <link type="text/css" rel="stylesheet" 
  <!--[if IE 6 ]>    
    <link type="text/css" rel="stylesheet" 

Test page, webpagetest results. No more blocking :)

Answering Andrea's question - what it if you have several conditionals - for IE6, IE7 and so on, I did one more test with two conditional CSS files. Turns out it's fine, as long as there's one conditional comment before the CSS. I actually updated the comment so it checks for all IE versions.

Test page, results, code:

<!--[if IE]><![endif]-->
<html lang="en">
    <title>base page</title>
    <link type="text/css" rel="stylesheet" 
    <!--[if IE 6]>    
        <link type="text/css" rel="stylesheet" 
    <!--[if IE 7]>    
        <link type="text/css" rel="stylesheet" 

In conclusion #2... conditional comments cause CSS to block. The workaround it to have an extra empty comment before the blocking CSS, or, to be safe, right after the doctype. Even better - don't use conditional comments at all. Except for browser-sniffing and loading two complete and completely separate CSS files, not just the IE fixes.

Tell your friends about this post: Facebook, Twitter, Google+

59 Responses

  1. what if you put the if IE 6 or lte 7 at the end of the page after the body?

    That would be “just a comment” for standard browsers, a CSS “fixer” for IE 6 or 7.

    It’s quite common technique to write a standard CSS file and then overwrite some selector to fix IE6 inconsistencies, the fact we have to respect the order means redundant files/bandwidth for the server, isn’t it?

  2. Andrea, that would be possible, but will not allow the page to render progressively in IE67. The browser waits for all CSS to arrive (all but Opera do) before starting to render (test: That means IE67 users will look at a blank page till the final css (and therefore all JS) is downloaded.

    That’s why to fix ie6 inconsistencies, the _ hack (and * for IE7) is your friend :) It stays in the same selector and is easy to spot and problematically parse and delete once IE6 is no longer around

  3. Hi, Nice one.

    but luckily I prefer to use server side browser sniffing and then include the corresponding css file,

    works like charms.

    Thanks for the insight

  4. Markus LeptienM

    Hi Stoyan!

    Thanks for your comments and correction! I updated my blog entry, now with a different solution.

    Kind regads,

  5. Thanks for the update on this. I generally only use conditional comments to load a PNG fix. It should be fine to move it before all other files in the head thus negating the slowdown.

  6. Stoyan, I thought the problem was to avoid IE8 slow down … I am a bit sick to care that much about users/companies stuck in the past with their buggy+un-secure browsers (and for no valid reasons) but you are right, that is a side effect to mention :-)

  7. Andrea, yes, the problem is slow down in IE8. But the problem is caused by a solution for IE6 or 7 suggested by the vendor of IE8 :)

    Anti-pattern: solution that causes more problems than it solves :P

  8. “Best – just use _ and * hacks, go with a single CSS and forget sniffing.” Dear sir, I regret to say that your advice here is astonishingly stupid so I strongly recommend you not to do frontend development at all or at least remove this offending line from your post. Thank you.

  9. My variation of Paul’s pattern works out of the box:

    Instead of applying classes to the body, I apply them to the HTML element. No need for empty comments.

  10. @rob ahaa! good one

  11. I’m a big believer in conditional comments around the body, so I will definitely be recommending Rob’s fix internally at Move. Although I’d put it nicer, I’d agree that going with the * and _ route is probably not a great idea. It’s far less readable for those that don’t have a full understanding, and it may not be as viable long-term (I know what you’re thinking). That said, having everything in one CSS is the way to go from both a performance and a maintenance perspective. Thanks Stoyan and others for this.

  12. Here is my bloated variation of this trick:

  13. Here’s the start of a method to enable developing multiple “full alternative” versions of browser-targeted stylesheets rather than the usual IE override technique. It uses diff, plus the Compass authoring toolset a “CSS meta-framework” (which in turn is based on Sass). This allows you to maintain ALL your style code in a single source file, and compile/output different versions of standard CSS by using variables, conditionals and other real programming features within your CSS. Feedback please – hansbkk [at] gmail

  14. The ideal solution, IMO, is to avoid browser targeting for all but IE 6 which is filtered nicely with * html. Unlike hacks, it takes advantage of fundamental flaws in IE6′s idiot-version of the DOM so it’s unlikely new features in the future will cause these statements to break anything.

    If you’re on a large team where not everybody knows enough to avoid IE 7 issues with non-browser-specific declarations, I don’t see any problem with a one-time browser sniff to target IE 6 and 7 problems. There’s no practical way to test by method for CSS problems and I find it considerably less hacky than touching IE-proprietary technology that (as we can see) makes an incredibly stupid oversight in turning comments into something other than a simple flag to tell the parser to ignore the contents.

    Also, branching CSS sheets makes maintenance a PITA. Browser targeting works best when the bad-browser declarations are side by side with the general declarations where everybody can see them and the targeting is handled in a consistent manner that makes it easy to yoink when Microsoft’s garbage browsers are finally no longer a going concern.

  15. Is it me or does this problem seem fixed in some IE8 update? When I execute the base page test mentioned at the beginning of this post, the problem doesn’t occur anymore. Nor can I reproduce the problem myself with a simple html file.

    If the base page hasn’t changed since the original test, I’m thinking Microsoft released an IE update, fixing this problem. Either that or something has changed in the IE installation.

    Original test:
    Test at aug. 31, 2010:

  16. Html5 Boilerplate uses these conclusions and includes in the code the conditional comments that you have shown. Thank you for the tests and the explanations!

  17. Instead of an empty conditional comment before the html element, place an dummy link element inside the comment, and place the comment at the beginning of the head element (where it lands in the DOM anyway):

       <!--[if IE]><link/><![endif]-->

    Then, you’ll fix 2-in-1: in addition to the conditional comment blocking, you also fix the issue that @import in IE behaves the same as having <link> at the bottom of the page. Thus, it fixes the probleem described here:

    The fact that a dummy link element fixes the @import problem in IE, was described 9 years ago:

  18. An alternative that appears to work without blocking is to set conditional classes on the <html> tag. Read further about it at:

  19. [...] Ok – so I can’t take any credit for this – but check out this blog post: [...]

  20. [...] Conditional comments block downloads Tweet Ссылки по теме: Если проблемы с IE [...]

  21. [...] aliados, si indagamos más en la web, podemos encontrarnos con grandes sorpresas, como ser que los comentarios condicionales bloquean las descargas (o en otras palabras, evitan la paralelización de descargas de hojas de estilo). En esta entrada [...]

  22. [...] This empty conditional comment hack is used to basically increase performance of your site. When conditional comments are used on your site, for example, for an ie6 conditional stylesheet, it will block further downloads until the css files are fully downloaded, hence increasing load time. To solve this issue, an empty conditional comment, like below, is used before any css is loaded in the document, and the problem will be solved! For further reading, check out this article. [...]

  23. [...] Stoyan Stefanov – Conditional comments block downloads [...]

  24. [...] The most significant mark-up change I made was moving the IE Conditional Comments from around the <body> tag to around the <head> <html> tag (thanks for the edit, Dan). I felt this not only better fit with the Modernizr approach, but also interfered less with the native WP $bodyclass functionality. As a fortunate side-effect, it also allowed me to remove the empty Conditional Comment from the <head> (there to prevent CSS blocking). [...]

  25. [...] grazie ai commenti, dovrebbe scaricare solo il 6 (come riportato su Webforscher’s Blog e su Ovviamente questo non dovrebbe succedere, ma spostando il tutto a inizio pagina si risolve il [...]

  26. [...] решить какой метод использовать, вы можете изучить статью рассматривающую то, как условные комментарии блокируют загрузки. В ней [...]

  27. [...] the CSS file has loaded. Fortunately, there is an easy workaround for this issue — just add an empty conditional comment [...]

  28. [...] particular, I was not aware that conditional comments block downloads in IE until the CSS file has loaded. Fortunately, there is an easy workaround for this issue — just add [...]

  29. [...] Posted by Ralph According to some tests, it seems IE8 gets slowed down by IE6 conditionals. Yes I read than here a while ago and it seems an empty CC at the top of the head cures the problem. Another reason I [...]

  30. Nice article with great tips. Had never thought IE8 gets it for download. Thanks for the nice solution and effort put in.

  31. I really found this article helpful. Had never thought IE8 gets it for downloading. Thank for your help.

  32. Nice solution, but I use PHP to detect a user’s browser and based on that data, I output the correct stylesheet and information. I understand this isn’t always an option, but for those that have access to and knowledge of PHP, this method is faster and will have fewer HTTP requests. Thanks for sharing this!

  33. IE has always been the thorn in the toe of the entire internet :(

  34. [...] – Empty IE conditional test boosts performance Came across this article this morning. Conditional comments block downloads / Stoyan's Reading through it, the key takeaway is that placing an empty conditional IE statement at the top [...]

  35. [...] Conditional comments block downloads / Stoyan’s [...]

  36. Fashion Advice for Indian Women…

    [...]Conditional comments block downloads / Stoyan’s[...]…

  37. This article is very helpful for me. Had never thought IE8 gets it for downloading. Thank for your help.

  38. Thank you for your post.Thanks Again. Will read on…

  39. Hey, thanks for the blog.Really looking forward to read more.

  40. free download nulled scripts…

    [...]Conditional comments block downloads / Stoyan’s[...]…

  41. DLEWORDPRESS is Free Download DataLife Engine Plugin Sharing website…

    [...]Conditional comments block downloads / Stoyan’s[...]…

  42. Dịch Vụ Thám Tử Nhanh Chính Xác Bảo Mật…

    [...]Conditional comments block downloads / Stoyan’s[...]…

  43. Is this same issue this site is stuck for a while in my IE 8?

  44. I dont support IEs long time ago !

  45. Great!

    Horrible IE 8….

  46. [...] when it's a CSS in conditional comment for IE [...]

  47. [...] This empty conditional comment hack is used to basically increase performance of your site. When conditional comments are used on your site, for example, for an ie6 conditional stylesheet, it will block further downloads until the css files are fully downloaded, hence increasing load time. To solve this issue, an empty conditional comment, like below, is used before any css is loaded in the document, and the problem will be solved! For further reading, check out this article. [...]

  48. To all those advocating server-side browser detection, you do realize, don’t you, that the UA string can be modified? Besides, we’ve been-there-done-that with browser detection in JavaScript back in the 90′s. Relying on the UA string is fragile, and inevitably it *will* break. It’s not a question of “if” but “when”.

    Conditional comments are superior because they rely on the rendering engine, which also, surprise, surprise directly effects what style you need to send down. With a conditional comment targeting IE6 for example, the only thing that will *ever* run that style is IE6. Even if I make Firefox send a UA string saying it’s IE6, it won’t get that IE6 style. Meanwhile, your sites will send style that will actually screw the Firefox rendering up because they’re too dumb to know it’s not really IE6.

  49. [...] Conditional comments block downloads / Stoyan’s phpied.comPrograms can have four styles of implementation comments: block, single-line, trailing … Block comments are used to provide descriptions of files, methods, data … [...]

  50. Er…I’m a Chinese student without great English skill. And I am a green hand in Web developing.
    I found this link from a book named “Stuning CSS3″.
    I want to konw what “main stylesheet” means.
    If it means the first one?
    What will happen if I provide 2 sheets for IE8 ? Both of them would block downloads?
    How would browser download these sheets ?If the first one would block the download of second one and the second one also block other downloads ?
    Or we should avoid using two sheets?

    Or could you tell me how I could test these out by myself.
    Looking forward for your reply.

  51. [...] [...]

  52. [...] performance for IE by preventing that browser’s inherent tendency to block downloads. See Conditional comments block downloads for more [...]

  53. [...] Stefanov took up the cause on May 23, 2010 with his post where he outlines the even curiouser case of IE blocking downloads even if the conditional comment [...]

  54. [...] 这个空的注释语句主要用来提高网站的载入速度。如果网站中使用了条件注释(例如针对IE6的条件样式表),条件注释将阻止其它文件下载,直到CSS文件下载完成为止,致使页面载入速度降低。为解决这个问题,只需在文档中载入CSS链接的前面添加像下面的空条件注释。更多详情请查看Conditional comments block downloads。 [...]

  55. you will discover a pair of puma Ferrari position which is to be the right diamond necklace fit your needs.

  56. ルイヴィトン バッグ 新作2013

  57. […] Hack para cargar la página más rápido Este hack de comentario condicional vacío se utiliza básicamente para incrementar el rendimiento de tu sitio. Cuando se utilizan comentarios condicionales en tu sitio, por ejemplo para una hoja de estilo condicionada a IE6, se bloquean el resto de descargas hasta que los archivos CSS se han descargado completamente, incrementando por tanto el tiempo de carga. Para solucionar este problema, un comentario condicional vacío, como aquí debajo, se usa antes que se cargue cualquiera de los CSS en el documente, ¡y el problema se habrá resuelto! Para más información, mira este artículo. […]

  58. Are these conditional comments still relevant, now that responsive themes are generally the norm? I run a wordpress site and I have multiple conditional comments, which I’m sure are slowing down the load times.

  59. Awesome issues here. I’m very satisfied to seee your post.
    Thank you a lot and I am taking a look forward to contact you.
    Will you please drop mee a mail?

Leave a Reply