Notes of Maks Nemisj

Experiments with JavaScript

Conditional ie comments in react.js

Sometimes easy things appear to be more complicated, than initially thought. For example conditional IE comments in HTML, which I had to add today to a code I write.

At my work we have to support Internet Explorer browser version 9 an higher . In order to use media-queries we decided to use https://github.com/weblinc/media-match polyfill library.

What can be easy than that. Just add a conditional comment <!–[if lte IE 9]> and that’s it.

<!--[if lte IE 9]>
    <script src="/public/media.match.js">
 <![endif]-->

But things appear to be a bit more complicated, due to the React.js and isomorphic SPA which we build.

Unfortunately React.js doesn’t render HTML comments if you put them inside jsx file. In our architecture we have main HTML.jsx component which renders the whole HTML page on the server. So the solution I tried as the first one just didn’t work out:

renderHead: function() {
  return (
    <head>
      <!--[if lte IE 9]>
      <script src="/public/media.match.js"/>
      <![endif]-->
    </head>
  );
}

index.jsx

The only possible way to render HTML comments within jsx was to use dangerouslySetInnerHTML attribute of rect.’s and put that comment in there:

renderHead: function() {
  return (
    <head dangerouslySetInnerHTML={{__html: '<!--[if lte IE 9]><script src="/public/media.match.js"></script><![endif]-->'}}>
    </head>
  );
}

index.jsx

Also note that actually <script> tag must be closed separately, since the shortened version will not work correctly in the rect.’s and you will receive js errors.

The last but not least problem is that this will not work, if you have more than one item inside the <head> tag. Ofcourse you could put the whole html string also inside dangerouslySetInnerHTML, but imho that looks lame.

That’s why I’ve abused the forgiveness of the browser’s html parser and placed the conditional comment inside the <meta> tag, which works perfectly now.

, , , , ,

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.