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 YAHOO.env.ua for browser detection.


applyStyles: function(rawHTML) {
if (YAHOO.env.ua.gecko > 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){
return;
}
}
var newStyleEl = document.createElement('style');
newStyleEl.type = 'text/css';
if (YAHOO.env.ua.ie > 0){
newStyleEl.styleSheet.cssText = styles[i];
} else {
var cssDefinitionsEl = document.createTextNode(styles[i]);
newStyleEl.appendChild(cssDefinitionsEl);
}
headEl.appendChild(newStyleEl);
}
}
Njoy.