Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamically adding @font-face rule in IE 8 and less

I'm adding @font-face rules using IEs stylesheet.addRule() method. However, the @ symbol is a disallowed character for the 'selector' argument of that method so I'm getting a 'invalid argument' error.

s.addrule("@font-face", "font-family: 'Font Name'; src:url('/fonts/font.eot') etc...)";

Is there some other way to dynamically add these rules?

I've tried setting the innerHTML property of the style element, setting the cssText property of the styleSheet property, and appending a text node to the style element as well (which crashes IE).

Any other methods to try?

like image 835
Andy Hume Avatar asked Oct 28 '11 15:10

Andy Hume


1 Answers

Setting the cssText property does work, but you MUST insert the style element into the document before adding the @font-face rule to the document. Eg...

var s = document.createElement('style');
s.type = "text/css";
document.getElementsByTagName('head')[0].appendChild(s);
s.styleSheet.cssText = "@font-face {" + rule + "}";

As far as I can tell it is perfectly possible to set other types of CSS rules before inserting the style element into the page, but not @font-face.

Eg... this works fine:

var s = document.createElement('style');
s.type = "text/css";
s.styleSheet.cssText = "body { background: red}";
document.getElementsByTagName('head')[0].appendChild(s);

But this crashes IE 8 and less:

var s = document.createElement('style');
s.type = "text/css";
s.styleSheet.cssText = "@font-face {" + rule + "}";
document.getElementsByTagName('head')[0].appendChild(s);
like image 88
Andy Hume Avatar answered Oct 10 '22 10:10

Andy Hume