Best practice for defining CSS rules via JavaScript

Posted by Tim Whitlock on Stack Overflow See other posts from Stack Overflow or by Tim Whitlock
Published on 2010-04-03T08:38:10Z Indexed on 2010/04/03 8:43 UTC
Read the original article Hit count: 520

Filed under:
|
|
|

I'm loading a stylesheet that is only required when javascript is enabled. More to the point, it mustn't be present if JavaScript is disabled. I'm doing this as soon as possible (in the head) before any javascript libraries are loaded. (I'm loading all scripts as late as possible). The code for loading this stylesheet externally is simple, and looks like this:

var el = document.createElement('link');
el.setAttribute('href','/css/noscript.css');
el.setAttribute('rel','stylesheet');
el.setAttribute('type','text/css');
document.documentElement.firstChild.appendChild(el);

It's working fine, but all my CSS file contains at the moment is this:

.noscript {
    display: none;
}

This doesn't really warrant loading a file, so I'm thinking of just defining the rule dynamically in JavaScript. What's best practice for this?. A quick scan of various techniques shows that it requires a fair bit of cross-browser hacking.

P.S. pleeease don't post jQuery examples. This must be done with no libraries.

© Stack Overflow or respective owner

Related posts about JavaScript

Related posts about Performance