Friday, 6 March 2009

Dynamically loading CSS in Safari and Google Chrome

Having developed a new AJAX enabled content viewer for a client's website I found that it would not load correctly in Google Chrome or Safari. The content being loaded into the viewer DIV included the CSS styles for the content and the HTML content itself, by loading the CSS into the container DIV it was being loaded outside of the document header - this is not valid in Safari as all style definitions must be placed in the head section - as a result the content loads without any CSS being applied.

To fix this the AJAX request has been split into two requests, the first loads the HTML into the DIV, the second loads the CSS and writes it into a style tag in the head section - this works in all browsers. Unfortunately this isn't as easy as it sounds due to various browser quirks when creating style elements, populating the element and adding it to the head section.

Essentially the following code will ensure the style element is created correctly:

function addCss(cssCode)
var styleElement = document.createElement(”style”);
styleElement.type = “text/css”;
if (styleElement.styleSheet)
styleElement.styleSheet.cssText = cssCode;

Nicholas Zakas explains this in great and excellent detail:

No comments: