8

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?

6
  • Why no conditional comments? Further more your style-string is quoted wrong. And from tbe spec on msdn, isn't the signature ...(selector, style [, index]) ? Commented Oct 28, 2011 at 16:24
  • How do conditional comments help? Yeah, the function signature is as you state - have I done something wrong? It works fine in Webkit incidentally. Commented Oct 28, 2011 at 16:36
  • Conditional comments provide a way to specify CSS to apply only to IE or specific versions thereof. Example: <!--[if IE]><style type="text/css">@font-face { font-family: 'Font Name'; src: url('/fonts/font.eot'); }</style><![endif]--> Commented Oct 28, 2011 at 18:05
  • @font-face isn't a valid selector. Take a look at the description of the parameters on msdn.microsoft.com/en-us/library/aa358796(v=vs.85).aspx Commented Oct 28, 2011 at 18:06
  • Yes, I know what conditional comments are. I'm asking how do they help insert @font-face rules dynamically with JavaScript? Unless I'm missing something, they don't. Commented Oct 29, 2011 at 16:45

1 Answer 1

6

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);
Sign up to request clarification or add additional context in comments.

1 Comment

Chrome tells me 'styleSheet' is undefined. 'cssText' seems to be a property of s.style however. With that said, it doesn't insert anything into the <style> tag =/

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.