VML in all IE versions from 6 to 9

I've recently had an idea for a jquery plugin that required to show some vector graphics in a browser. In all major browsers you can use SVG for that purpose and in IE we have VML. And it works pretty well too in IE6 and and IE7, but with introduction of Standards Mode in IE8 things got ugly. After half a day of searching, trials and error I was able to come up with a piece of code that enables VML across all necessary IE versions.

Here it is:

document.namespaces.add('v',"urn:schemas-microsoft-com:vml", "#default#VML");
if(!document.documentMode || document.documentMode < 8) {
    var styles = document.createElement('style');
    styles.type = "text/css";
    styles.styleSheet.cssText ='v\:*{behavior: url(#default#VML);}';

However problems don't end there. In IEs 6 and 7 you were able to create VML elements just like any other DOM element with document.createElement(), however in IEs 8 and 9 creating a special stroke or fill elements causes error. Fortunately fix for that is relatively simple — just construct vml element as a string and insert it using insertAdjacentHTML() function like shown here:

var vml =
    '<v:shape path = "m 0,0 l 0,200, 200,200, 200,0 x e" coordsize="200 200"'+
    ' style="position:relative;width:200px;height:200px;display:block;>"'+ 
    '<v:fill type="gradient" color="#3399ff" color2="#0066cc" angle="270"/>'+
document.getElementsByTagName('body')[0].insertAdjacentHTML('beforeEnd', vml);

See the demo

Social comments Cackle