开发者

Best practice for defining CSS rules via JavaScript

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('t开发者_StackOverflow中文版ype','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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜