views:

51

answers:

1

There seems to be a bug in IE when cascading dynamic stylesheets. Does anyone know if there is a workaround? Consider this:

<head>
    <style>#test{background:red;}</style>
</head>
<body>
    <div id="test">test</div>
    <script>
        var link = document.createElement('link');
        var style = document.getElementsByTagName('style')[0];
        link.rel = 'stylesheet';
        link.href = 'test.css';
        style.parentNode.insertBefore(link, style);
    </script>
</body>

The injected 'test.css' contains #test{background:green}.

Even though we place the <link> before the <style> tag, IE7+ will override the styles with the injected stylesheet and apply green as background.

FF/Chrome do this the right way and lets the style tag take precedence over the injected link tag so the background stays red.

A: 

I think the cause for this is the way IE defines insertBefore. In IE only you may pass only one parameter into the insertBefore method and it will behave the same as appendChild. I think what they do is insert it THEN move it. If they render at the point of insertion then it would be rendering properly.

The only work around I can think of is as follows (which isn't ideal):

    var link = document.createElement('link');
    var style = document.getElementsByTagName('style')[0];
    var newstyle = style.cloneNode(true);
    link.rel = 'stylesheet';
    link.href = 'test.css';
    style.parentNode.insertBefore(link, style);
    style.replaceNode(newstyle);
sparksm
Yes, I did something similar in the end. I "touched" all link and style elements on the page after injection.
David