Friday, June 22, 2012

Getting around the 31 stylesheet limit in IE

Internet Explorer 9 has a bug which means it can't process more than 31 top-level stylesheets. (This actually affects 7 and 8 as well, but people are really good about updating Internet Explorer, aren't they? What's that? Oh)

The problem comes from the way IE stores CSS rules. Each rule is referenced as a 32 bit number. The first 5 bits are the ID of the top level stylesheet the rule came from, and the last 12 bits are the rule. The 15 bits in the middle are @import references. You can chain @imports three levels down (so 5 bits each again), but only from those first 31 stylesheets.

Now, it might seem quite odd to want to link 31 stylesheets, but given the way sites are built up from 3rd party code it's not that uncommon. Where I work now we provide just such a third party service  (advertising) and our styles were getting ignored by the browser because there were more than 31 stylesheets above ours (we load all our stuff on DOMContentLoaded from a Javascript tag, so there's not much chance to fix the load order.)

I came up with a (what I think is a) neat fix for this. We simply copy the CSS into a JavaScript file as a string and load that, then append the that string to the cssText property of one the existing stylesheets in the page like so:

document.styleSheets[0].cssText += ourCss;


The browser now processes the CSS, without busting its 31 stylesheet limit. You can't use this to insert an @import however as that isn't strictly cssText, it doesn't get reprocessed.

No comments:

Post a Comment