Is there an equivalent eval for css styles?

I have a style element that is being loaded from an external resource, and I want to apply its styles without nesting it in a string.

For example, it will <link rel="stylesheet" type="text/css" href="my.css" />load the css file and apply it without putting it inline, and <script src="zepto.js"></script>will do the same for javascript.

If you download the external js bit, you can evaluate it with eval(), even if it frowned.

But when you load the external style bit, I don’t know how to evaluate it, except to add it to dom.

So, is there a similar function for styles, like eval for scripts? Does anyone know a good hack to get the same effect?

Everything is fine until the style is applied, until it appears in dom.

+4
source share
2 answers

You need to create an styleadd in tag headand then install the full css content in innerHTML.

Example:

var style = document.createElement('style');
style.type = 'text/css';
document.getElementsByTagName('head')[0].appendChild(style);

//here is the magic.
style.innerHTML = 'put the css content'; 
//Ex: style.innerHTML = '.cssClass { color: #F00; }';
+2
source

You have two options:

  • JavaScript parses JavaScript. For example, Node.js has pure JS CSS parsers, e.g. http://github.com/reworkcss/css . I do not even know its quality.

  • To add these styles to the DOM as the content of an element <style>and set it style.disabled = trueso that its rules do not affect the current content.

+1
source

All Articles