当前位置: 动力学知识库 > 问答 > 编程问答 >

javascript - dynamically load css approaches

问题描述:

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.

网友答案:

The primary reason you wouldn't see this approach mentioned or suggested anywhere is largely because it's unnecessary. Instead of constantly trying to edit style elements, you should have a set of classes that you add and remove from elements dynamically.

In my experience, dynamically adding a style element with text works cross browser. So far I haven't found a browser that doesn't work with something like:

//jQuery for brevity
$('<style>p{margin:0}</style>').appendTo('head');

The only situation I've ever needed this in was for adding a large set of very specific styles for usage with a bookmarklet. Otherwise, I'll dynamically add a stylesheet:

$('<link rel="stylesheet" type="text/css" href="path/to/stylesheet.css />').appendTo('head');

But really, stylesheets should already exist within the HTML.

网友答案:

Use YepNope lib, it will do the dirty stuff for you. And it's only 1.7kb when gzipped and minified.

分享给朋友:
您可能感兴趣的文章:
随机阅读: