views:

43

answers:

1

I have a problem with adding a dynamic style element with @import statements for IE. Try this:

var string = '@import url(test.css)';
var style = document.createElement('style');

if (style.styleSheet) { // IE
    style.styleSheet.cssText = string;
} else {
    var cssText = document.createTextNode(string);
    style.appendChild(cssText);
}

document.getElementsByTagName('head')[0].appendChild(style);

This works for FF/Chrome but not IE. It seems to recognize style.styleSheets.imports, but it will not apply the imported stylesheet. Is this a bug or limitation?

A: 

Many older browsers can't process varying forms of the @import directive, this can be used to hide css from them. Check http://www.w3development.de/css/hide_css_from_browsers/import/ for details.

The @import directives must come first in a style sheet, or else they'll be ignored. however IE doesn't ignore misplaced @import directives.

Edit: See the addImport method for injecting style sheets in IE.

melhosseiny
This is not the issue here, it works fine when adding a style tag in the HTML, the problem arises when injecting via DOM.
David
Check edited answer.
melhosseiny