HTML5 Shim – Enabling HTML5 on Internet Explorer 8 or below

Chetan Singh  April 14, 2012


So here we are with HTML 5 that provides us with some amazing tags :-

<header><article><section><aside><details><footer> etc...

Most modern browsers support HTML 5 to a certain extend but what about our dear friend IE ?

We can have a quick look at how well different Browsers support HTML 5 here and to the fact it is not at all surprising that IE has the least support for HTML5.

So how can we use all these amazing HTML5 features in IE 8 and below. Here HTML5 Shim (or Shiv) comes to our rescue.

Lets just try to see things using a sample code below in which we use an HTML 5 <header> tag and giving it some styling through CSS.

<!DOCTYPE html>
<html>
	<head>
		<title>HTML Shim</title>
		<style>
			header{
				background:#ff0000;
			}
	</style>
	</head>
	<body>
		<header>
			<h1> My Sample Heading</h1>
		</header>
	</body>
</html>

Here is what we get,…

html-shim

 

The problem with IE 8 and below is that it doesn’t recognize the <header> tag and so the CSS Engine is not able to apply the CSS rule.

So what we need to do, lets see. We add this following code in our head.

<script>
	document.createElement('header');
</script>

And now run again. Here we see it works for IE. What we did?? We just told IE to create a new element named “header” and then the CSS Engine starts recognizing it and applies styling to it.

So do we need to this for all the various HTML5 tags we are planning to use??

No not at all, here is something at our rescue again. We just need to add below line of code to the head and thats it, all done !!

<!--[if lt IE 9]>
<script src="//html5shiv.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->

For more info on this, you can view html5shim.

What this script does, it creates the Elements which are there in HTML5 so we can use in IE 8 and below.

Note the use of

<!--[if lt IE 9]>

It just enables the script to load only when Browser Version is below IE 9.
So it saves us  a request to the script if we are viewing the page on any other browser.

So here is what our final piece of code look like.

<!DOCTYPE html>
<html>
    <head>
        <title>HTML Shim</title>
        <!--[if lt IE 9]>
            <script src="//html5shiv.googlecode.com/svn/trunk/html5.js"></script>
        <![endif]-->
        <style>
            header{
                background:#ff0000;
            }
        </style>
    </head>
    <body>
        <header>
            <h1> My Sample Heading</h1>
        </header>
    </body>
</html>

Enjoy !!!

Chetan Singh


Next post: