Best practice for defining CSS rules via JavaScript
- by Tim Whitlock
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.