views:

112

answers:

1

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.

+1  A: 

Hmm. If saving a few bytes of bandwidth is not an issue, why not load all stylesheets, but prefix all classes in the JavaScript one with a specific class:

body.hasjs a { color: blue }
body.hasjs div.contactform { width: xyz; }

serve the body without that class

<body>

and add a tiny JavaScript that adds the class name, something like:

body.onload = function() {
document.body.className = "hasjs"; 
}

to get the switching process even more early, you could look into one of the native Javascript onDOMLoad solutions.

Pekka
setAttribute is broken in Internet Explorer — it will fail whenever the attribute being set has a name that isn't identical to the property that maps on to the same value. Since class is a reserved keyword, the property is called className, so this breaks. Use foo.className = 'value'.
David Dorward
There is no need to set an id on the body. Access it with `document.body` instead.
David Dorward
That's neat, I hadn't thought of using a high level selector like that. It would be better to serve with class "nojs" and then remove the class as early as possible with JS enabled
Tim Whitlock
@Tim good point, it also depends a bit which style sheet is larger, the JS or no-JS one. To completely avoid conflicting definitions (that could happen through one stylesheet defining a generic rule that is not overwritten by the other), you could also completely separate the style sheets into `.hasjs` and `.nojs` namespaces and give the body a `nojs` from the start as you suggest.
Pekka