Friday, November 16, 2007

IE issue - style tag embedded in ajax response not parsed

While working on a recent project, my rails application was returning a html snippet with an embedded style tag in response to an ajax request. Firefox displayed the updated html content perfectly, but IE refused to play nice.

This issue is documented here and a solution has also been provided. I use YUI so I updated the code to use for browser detection.

applyStyles: function(rawHTML) {
if ( > 0) return;
var headEl = null; // lazy-load

// find all styles in the string
var styleFragRegex = '<style[^>]*>([\u0001-\uFFFF]*?)</style>';
var matchAll = new RegExp(styleFragRegex, 'img');
var matchOne = new RegExp(styleFragRegex, 'im');
var styles = (rawHTML.match(matchAll) || []).map(function(tagMatch) {
return (tagMatch.match(matchOne) || ['', ''])[1];

// add all found style blocks to the HEAD element.
for (i = 0; i < styles.length; i++) {
if (!headEl) {
headEl = document.getElementsByTagName('head')[0];
if (!headEl){
var newStyleEl = document.createElement('style');
newStyleEl.type = 'text/css';
if ( > 0){
newStyleEl.styleSheet.cssText = styles[i];
} else {
var cssDefinitionsEl = document.createTextNode(styles[i]);

1 comment:

Anonymous said...

Maybe you should consider the IE limitation on the number of properly applied style tags. If you have more than 30 stylesheets (this includes each and every single style tag added by you, plus 'link rel="stylesheet"...' tags), the styles after the 30th in order of their definition in the 'HEAD' won't be used!
Refer to:

A possible workaround is to consolidate your dynamic styles into a single one.