Saturday, June 30, 2007

Nicholas C. Zakas: dynamically inserting CSS into your page

Itt van az egesz, de a lenyeg:

Safari requires dynamically created <style/> elements to be inserted into the for the rules to be applied

When IE encounters style.appendChild() it throws the rather obtuse and not-very-helpful error message, “unexpected call to method or property access”. Try replacing that with a call to set innerHTML, and you’ll get an equally useless error message of “unknown runtime error”. What’s going on here? It turns out that IE won’t let you manipulate <style/> elements in this way. There is, however, a different way to do the same thing. IE supports a styleSheet property on each style element that allows for the manipulation of the style sheet and the rules contained within. The styleSheet property has a property called cssText, which can be used to set and retrieve the CSS text for the style sheet.

This code now works in all A-grade browsers:

function addCss(cssCode) {
var styleElement = document.createElement(”style”);
styleElement.type = “text/css”;
if (styleElement.styleSheet) {
styleElement.styleSheet.cssText = cssCode;
} else {
styleElement.appendChild(document.createTextNode(cssCode));
}
document.getElementsByTagName(”head”)[0].appendChild(styleElement);
}

A warning: IE only allows writing to styleSheet.cssText one time per <style> element. If you try to do it more than one time, it can crash the browser. For this reason, it’s best not to reuse <style> elements on your page. Instead, remove them or just add new ones.

A commentek kozul:

According to the HTML 4.01 spec section 14.2.3, style tags must be contained in the head element: “HTML permits any number of STYLE elements in the HEAD section of a document.”

Link to the spec:
http://www.w3.org/TR/html401/present/styles.html#edef-STYLE