Optimal way to insert X-UA-Compatible

Published 2012-02-01 03:05 by Leif Halvard Silli

Do this:

<!--[if i]><![endif]-->
<!DOCTYPE html><html><head>
<!--[if ie]><meta http-equiv=X-UA-Compatible content="IE=Edge"><![endif]-->

Why:

  1. HTML5-valid: It is conforming HTML5.
  2. <!--[if i]><![endif]--> does two things: It prevents some kind of download blocking, in Internet Explorer. And, more important in our context: Without it, the second conditional comment does not work.
    • NOTE! I did something extra… I did not write [if IE] — I wrote [if i], which to IE is equivalent to [if !IE]. This is almost entirely unimportant — it just saves one character…
  3. <!--[if ie]><meta http-equiv=X-UA-Compatible content="IE=Edge"><![endif]--> — the only thing to say is that without the empty, conditional comment before the DOCTYPE (see previous point), this conditional comment does not work.

Advantages

It’s all in the DOM. Let’s examine the alternatives:

  • You could skip the first conditional comment and just leave it as is. However, this simply does not work.
  • You could have skipped the first conditional comment, and instead moved the second condintional comment before the DOCTYPE. However, IE versions without support for x-ua-compatible would then enter quirks mode, because it saw something — the meta element — before the DOCTYPE.
  • You could have skipped the first conditional comment and moved the second conditional comment before the DOCYPE and inserted a DOCTYPE inside the conditional comment. However, this would have resulted in two DOCTYPE nodes in the DOM of IE.
  • You could have used a conditional code variant that only targets IE8 and above. However, the syntax for that is so hard to remember …

Why user x-ua-compatible at all?

Why indeed. It – hopefully – avoids that IE jumps to a legacy mode, without your awareness.

Another alternative, that I would not use: HTTP header.

Some claim that you should send the x-ua-compatible pragma as an HTTP header instead of including it in your code. This, in order to stay HTML5-valid. Well, I tried that — and it caused some weired problems, actually. (It affected — strangely enough — the source, uppercasing the code when saving and other things — should probably write an article about that, to document that I am not insane or something …)

Other things: IE10 won’t support conditional comments

Look forward to that day!


|