Sunday, January 23, 2011

How to make HTML5 work on IE

I am sure that by now, you must have heard about HTML5. In the web-world HTML5 and CSS3 are getting a lot of attention. All of the browser developing companies/communities are working hard to make their browsers compatible with HTML5 soon. Even IE9 is going to support a lot of HTML5/CSS3 standards. But still the question is how we can make HTML5 semantics work on the old school browsers like Internet Explorer version less than 9.

The significant difference between HTML5 and HTML4/XHTML1 is that we can use custom tags in HTML5. Tags like <header>, <footer>, <section>, <nav> and so many others work in HTML5. A simple syntax for a HTML5 page is as follows:

<!DOCTYPE html>
<html>
<head>
    <title>HTML5 on IE</title>
     <style>
          red { color: red; }
    </style>
</head>
<body>
    <section>
        <red>This should be red in color</red>
    </section>
</body>
</html>
Notice that in this code, we have included a custom tag named 'red'. A style has been added to this tag. If this page is viewed on a HTML5 supporting browser (like Safari), then the text in the 'red' tag should be displayed as red in colour.

On Safari4, it would be displayed as:


whereas if the same page is viewed on Internet Explorer (even on IE8), the style would not be reflected and the text will be displayed simply as:

The fix is as follows:
The reason of the issue is that IE is unable to understand our custom tag 'red'. So to make IE understand our tag, we have to use a simple javascript as follows:

document.createElement('red');

In this simple line of code we have created a new element named 'red'. Now the 'red' can be used as a tag name in our HTML code. So, the code becomes:

<!DOCTYPE html>
<html>
<head>
  <title>HTML5 on IE</title>
  <style>
    red { color: red; }
  </style>
  <script>
     document.createElement('red');
  </script>
</head>
<body>
    <section>
        <red>This should be red in color</red>
    </section>
</body>
</html>

...and it is displayed perfectly on IE as:

This solution is a good deal, if you have very few number of custom tags. Simply add this JavaScript line for each of the custom tag and you are good to go. But, then what is the use of HTML5 if we are going to use very few custom tags? The real power of HTML5 lies in it's custom tags.

Fortunately, we have a solution for that too. Remy Sharp has put a great effort in creating a javascript file which can be used to solve this problem. Simply include this javascript and you don't have to create elements for each of the custom tags.

This javascript is also hosted on Google Codes and thus, it can simply be included as:
<!--[if lt IE 9]>
<script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->

Happy coding!

No comments:

Post a Comment