I have long known that you can load style rules into a page dynamically by using addRule() and insertRule(), depending on whether it is IE or a standards compliant browser. But I just discovered that on Chrome, a much more generally-useful (for me) approach works just fine: create a style element, add a texnode to it with arbitrary css text (it could be the contents of a css file), then add that to the document. You can also remove it by removing that style node from the document. For instance this function works fine when I send it the string "div {background-color: red; }\n p {font-family: georgia; }":
var applyCss = function (cssString) {
var scriptNode = document.createElement('style');
scriptNode.appendChild(document.createTextNode(cssString));
document.getElementsByTagName('head')[0].appendChild(scriptNode);
return scriptNode;
};
While I understand the benefits of doing it on a rule basis in some scenarios, this shortcut (which is kind of analogous to using innerHTML instead of building elements part by part using DOM techniques) would be particularly useful to me in a lot of situations if I can count on it working.
Is it consistently supported? Is there any downside to this approach? I'm particularly curious because I've never seen this approach suggested anywhere.